Search code examples
javabyte-buddy

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


I wonder if using byte-buddy i can crate method in class

public class Foo {

  //some fields and getters 

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

so that it will invoke

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

I have tried

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

and adding @This to parameter in FooPrinter but i receive exception that non of methods in FooPrinter allows for delegatrion from Foo.bar().


Solution

  • 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.