Search code examples
javabytecodeinstrumentationbyte-buddy

How to rebase an interface default method with ByteBuddy?


I'm trying to annotate a default method at runtime using ByteBuddyAgent. In order to keep the default implementation, I'm using a rebasing strategy, but I can't figure out how to intercept the new method with a call to the original one.

I tried using MethodCall.invokeSuper() and MethodCall.invokeSelf().onDefault(), but with both give me an IllegalStateException.

new ByteBuddy()
.subclass(MyInterface.class)
.method(isDeclaredBy(typeDescription).and(isDefaultMethod()))
    .intercept(MethodCall.invokeSelf().onDefault())
    .annotateMethod(AnnotationDescription.Builder
        .ofType(MyAnnotation.class).build())
.make()
...

Solution

  • You need to use SuperMethodCall.INSTANCE. This way, Byte Buddy gets a chance to locate the actual super method which is the rebased method.

    In your case, you would only invoke the same method recursively. Also, the onDefault configuration would attempt to invoke a default method on an interface implemented by MyInterface.