Search code examples
javabyte-buddy

Modifying the returned value of a static method


I need to intercept a method call to a static method. My new method needs to invoke the original implementation of the method, do some work with what it returns and return the modified value.

My problem is with the "invoke the original implementation of the method"-part, how do I do that? Some documentation reading and googling seems to show I need to use Advice with @Origin or @SuperMethod, but I've been unable to find out how to create an Advisor in a way that allows me to return a modified value.

Any pointers?


Solution

  • If you are using Advice, you have to use the advice-specific annotations:

    class SomeAdvice {
      @Avice.OnMethodEnter 
      static void enter() {...}
      @Advice.OnMethodExit 
      static void exit(@Advice.Return(readOnly = false) Object val) {
        val = "some other value";
      }
    }
    

    It seems like you are blending concepts of MethodDelegation into advice here. Those two are however very different. Advice adds code before and after a method, delegation replaces a method.