There must be something else to your setup, this works just as expected:
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";
}
}
}
will print someField custom string.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…