0

My use case is to implement a method that combines some fields with a string concatenation. Basically the equivalent of:

String doAThing(){
 return this.a + " " + this.b;
}

in the examples i can only find static values (for example the Stack Manipulation here https://github.com/raphw/byte-buddy/blob/master/byte-buddy-dep/src/test/java/net/bytebuddy/ByteBuddyTutorialExamplesTest.java )

Thanks!

Shaharko
  • 136
  • 1
  • 6

1 Answers1

0

If the fields that You want to join are known and don't need to be discovered dynamically You can try with @FieldValue:

public class Test {

    public static void main(String[] args) throws Exception {
        String name = Inner.class.getName() + "_bb";

        new ByteBuddy()
            .redefine(Inner.class)
            .name(name)
            .defineMethod("doAThing", String.class, Opcodes.ACC_PUBLIC)
            .intercept(to(new Interceptor()))
            .make()
            .load(Test.class.getClassLoader());

        Object instance = Class.forName(name).newInstance();
        Method m = instance.getClass().getMethod("doAThing");
        System.out.println(m.invoke(instance));
    }

    public static class Interceptor {
        public String doAThing(@FieldValue("a") @RuntimeType Object a, @FieldValue("b") @RuntimeType Object b) {
            return a + "_" + b;
        }
    }

    public static class Inner {
        private String a = "a";
        private String b = "b";
    }
}
kaos
  • 1,598
  • 11
  • 15