简体   繁体   中英

MethodDelegation with Passing Object Array to Specific Parameters Using ByteBuddy

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM