Search code examples
javainstrumentationbyte-buddyjavaagents

Byte Buddy Adding Try blocks to existing methods


Using Byte Buddy, I'm trying to add a few on @Advice.OnMethodExit and @Advice.OnMethodEnter. I would like to add blocks like this by the custom agent I'm building.

public String getSomeMethodName() {
        try{

// Default block of code present without instrumentation

        }finally {
// Some Code Snippets added by agent.
        }
    }

Basically the function does not even have try block. How can I add that as well as the finally block. Is it a good practice to do so? Or what is the best practice to achieve this?

What am trying is adding

try{ 

 }catch(){
 }

in OnMethod.Enter.

Would like to include finally block OnMethod.Exit.


Solution

  • Use @Advice.OnMethodExit(onThrowable = Throwable.class). This triggers the advice even if any throwable type was thrown what is the semantics of a finally block.