Search code examples
javabyte-buddy

Conditional method delegation using ByteBuddy


Is it possible to do a conditional call within bytebuddy's method delegation call? Suppose we have the following case:

Method serviceMethod = serviceHandler.getClass()
                .getDeclaredMethod(methodName, String.class, String.class, Object.class);
this.serviceHandler= byteBuddy.subclass(serviceHandler.getClass()).method(ElementMatchers.named("handleService"))
                .intercept(SuperMethodCall.INSTANCE.andThen(MethodCall.invoke(handleMethod).withArgument(0, 1, 2))).make().load(getClass().getClassLoader()).getLoaded().newInstance();

Can we do something like "only if super method call returns true then call subclasses method"? That would be a conditioned "andThen":

intercept(SuperMethodCall.INSTANCE.**andThenIfConditionFullfilled**(MethodCall.invoke(handleMethod)

Solution

  • No, it is not possible, unless if you implement your own Implementation. Conditional code quickly gets complicated. Byte Buddy is aiming for generating as little code as possible.

    Possibly, use Advice for a byte code template if you wanted to avoid delegation.