字节伙伴将实例方法委托给静态方法将实例作为参数传递

Byte-buddy delegating instance method to static method passing instance as a parameter

我想知道是否可以使用 byte-buddy 在 class

中创建方法
public class Foo {

  //some fields and getters 

  public String newMethod() {
    return FooPrinter.createCustomToString(this);
  }
}

这样它将调用

public class FooPrinter() {
  public static String createCustomToString(Foo foo) {
     return foo.getSomeField() + " custom string";
  }
}

我试过了

builder
    .defineMethod("newMethod", String.class, Ownership.MEMBER, Visibility.PUBLIC)
    .intercept(MethodDelegation.to(FooPrinter.class))

并将 @This 添加到 FooPrinter 中的参数,但我收到异常,即 FooPrinter 中的所有方法都不允许来自 Foo.bar().

的委托

您的设置一定有其他的东西,正如预期的那样工作:

import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.This;

public class Sample {

    public static void main(String[] args) throws Exception {
        Foo instance = new ByteBuddy().subclass(Foo.class)
                .defineMethod("newMethod", String.class, Visibility.PUBLIC)
                .intercept(MethodDelegation.to(FooPrinter.class))
                .make()
                .load(Foo.class.getClassLoader())
                .getLoaded()
                .getConstructor()
                .newInstance();

        Object result = instance.getClass().getMethod("newMethod").invoke(instance);
        System.out.println(result);
    }

    public static class Foo {
        public String getSomeField() {
            return "someField";
        }
    }

    public static class FooPrinter {
        public static String createCustomToString(@This Foo foo) {
            return foo.getSomeField() + " custom string";
        }
    }
}

将打印 someField 自定义字符串