0
interface Foo{
    Object foo(Object... args);
}

static class FooAdapter{
    Object foo2(String msg, Integer age) {
        System.out.println(msg+"=>"+age);
        return age;
    }
}

public static void main(String[] args) throws Exception{
    FooAdapter adapter = new FooAdapter();
    Foo foo = new ByteBuddy()
            .subclass(Foo.class)
            .method(ElementMatchers.named("foo"))
            .intercept(MethodDelegation.to(adapter))
            .make()
            .load(ClassLoader.getSystemClassLoader())
            .getLoaded()
            .newInstance();
    foo.foo("hello", 10);
}

My Code is simple, I just want Delegate My Foo interface foo method call to FooAdater instance foo2 method. But when i run test, ByteBuddy seems do nothing.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
BilboDai
  • 181
  • 2
  • 11

1 Answers1

0

The delegation is succeeding because Byte Buddy decides that Object::equals is the best method that can be bound to your adapter. It cannot bind the foo2 method, because it is expecting two arguments of type String and Integer while foo only declares Object[].

The delegator you want to define is:

Object foo2(@Argument(0) Object[] arguments) {
  System.out.println(arguments[0] + "=>" + arguments[1]);
  return arguments[0];
}

where the argument is bound correctly. Otherwise, you might want to use the MethodCall instrumentation where you can explode the array arguments. You need to use dynamic typing in this case as there is no way to prove that foo is invoked with a string and an integer.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • Thanks, I considered using bytebuddy instrumentation, but i found it quite hard for me to understand the abstraction of asm's. For example, i work it out with asm. Winterhalter would you give me some more doc about learning bytebuddy instrumentation? – BilboDai Jan 02 '17 at 09:34
  • You can start out with the documentation on bytebuddy.net. Beyond that there is a lot javadoc. – Rafael Winterhalter Jan 02 '17 at 10:51