Search code examples
javabyte-buddy

Unable to modify return value of method invocation using Byte Buddy


I wrote an agent using Byte Buddy and am attempting to modify the return value.

Agent code (partially pseudo code):

premain(String args, Instrumentation instrumentation) {
  new AgentBuilder.Default().disableClassFormatChanges()
          .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
          .type(ElementMatchers.is(target.class))
          .transform(
              (builder, typeDescription, classLoader, module) ->
                  builder
                      .visit(
                          Advice.to(CustomAdvice.class).on(ElementMatchers.named("methodName").and(ElementMatchers.isPublic()))))
          .installOn(instrumentation);
}


public class CustomAdvice {
  @Advice.OnMethodExit
  public static String intercept(@Advice.Return String value) {
    System.out.println("intercepted: " + value);
    return "hi: " + value;
  }
}

My Advice is working, but the return value from my advice isn't being used.


Solution

  • The solution was:

    public class CustomAdvice {
      @Advice.OnMethodExit
      public static void intercept(@Advice.Return(readOnly = false) String value) {
        System.out.println("intercepted: " + value);
        value = "hi: " + value;
      }
    }