Walter
Walter

Reputation: 1470

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.

Upvotes: 1

Views: 737

Answers (1)

Walter
Walter

Reputation: 1470

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;
  }
}

Upvotes: 5

Related Questions