Macko
Macko

Reputation: 21

How to catch return data with Byte Buddy and @Advice?

I know that method arguments are easy to catch, it is just using @Advice.AllArguments. Is it also that easy to catch return data from advised method ? My goal is not to modify methods at all, just 'take a picture of what comes in and what comes out' and write it to the file. The return type is mostly Response from javax, but sometimes primitives.

public class MyAdviser {

  @Advice.OnMethodEnter
  public static void onEnter(@Advice.This Object obj, @Advice.Origin String method,
        @Advice.AllArguments Object[] args) throws IOException {

    FileWriter fw = new FileWriter("AgentData.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);
    out.println(method);
    out.println("Arguments : " + Arrays.deepToString(args));
    out.println("---------------------------------------------");
    out.close();

    final Logger LOG = LoggerFactory.getLogger(obj.getClass());
    LOG.info("Method name : " + method + " Object  : " + obj + "   " + obj.getClass());
    LOG.info("Arguments : " + Arrays.deepToString(args));

  }

  @Advice.OnMethodExit
  public static void onExit(@Advice.Origin String method) {


  }
}

Upvotes: 1

Views: 1238

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44032

Just as mentioned in the javadoc of the Advice class:

@Advice.OnMethodExit
public static void onExit(@Advice.Origin String method,
                          @Advice.Return Object returned,
                          @Advice.Thrown Throwable thrown) {
  // thrown will be null if no exception was thrown, returned if it was
}

Upvotes: 1

Related Questions