Search code examples
javabyte-buddy

Method delegation on field and cast in Bytebuddy


Using Bytebuddy assume the following:

class Service {
    protected Handler handler;
...
}

interface Handler {
   public void handle();
}

class ConcreteHandler implements Handler {
    public void handle() {
       ...
    }
    public void handle2() {
       ...
    }
}

Generally we call the handle() method of Handler, but in some cases we need to call handle2() of ConcreteHandler's class which is it in runtime. Now the question: is that possible using Bytebuddy? Probably yes, but how?

i tried that:

if (condition) {
    MethodCall methodCall = (MethodCall) 
        MethodCall.invoke(methodHandle2).onField("handler")
                        .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC);
}

... but it fails with an IllegalStateException: Cannot invoke public void com.framework.ConcreteHandler.handle2(...) on protected com.framework.Handler com.framework.Service.handler

Any ideas?


Solution

  • This seems to be a bug in Byte Buddy. I hopefully fixed the issue in this commit which should resolve the issue in Byte Buddy 1.10.14. You can try the snapshot in the meantime.