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.
The delegation is succeeding because Byte Buddy decides that
Object::equalsis the best method that can be bound to your adapter. It cannot bind thefoo2method, because it is expecting two arguments of typeStringandIntegerwhilefooonly declaresObject[].The delegator you want to define is:
where the argument is bound correctly. Otherwise, you might want to use the
MethodCallinstrumentation where you can explode the array arguments. You need to use dynamic typing in this case as there is no way to prove thatfoois invoked with a string and an integer.