-1

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Hugi
  • 202
  • 2
  • 7
  • 2
    Not sure if I understand your requirement correctly, but my guess: Spring AOP could help on that. – Stultuske Jan 23 '18 at 09:12
  • 1
    Yes, I do agree with @Stultuske. Some `@Around` advice should do the trick – DamCx Jan 23 '18 at 09:15
  • @DamCx I was more thinking about an 'after return' :) – Stultuske Jan 23 '18 at 09:16
  • I would Google Rafael Winterhalter and @Supercall, for example take a look at his solution here: https://groups.google.com/forum/#!topic/byte-buddy/x1w1oOv3bhk Or maybe just send him a message. – Gonen I Jan 23 '18 at 09:38
  • I think with ByteBuddy only way to intercept static method is through Java Agent: https://stackoverflow.com/questions/34479909/change-behaviour-of-static-method-in-java-byte-code-manipulation. – kaos Jan 23 '18 at 10:47
  • Can you show some code? – Abhijit Sarkar Oct 18 '20 at 23:37

1 Answers1

2

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.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • Awesome, readOnly = false on @Advice.Return was the first missing piece in the puzzle. Only one thing left—how can I invoke the original method? (i.e. the method I haven't added the Advice to). – Hugi Jan 24 '18 at 09:33
  • 1
    It is invoked between the enter and the exit advice unless you skip it (see `@OnMethodEnter` javadoc). – Rafael Winterhalter Jan 24 '18 at 09:42
  • Dear lord… Of course. My brain today not brain well. Thanks for your help! – Hugi Jan 24 '18 at 12:44