如何使用Byte Buddy和@Advice捕获返回数据?

时间:2017-03-06 16:20:47

标签: java javaagents byte-buddy

我知道方法参数很容易捕获,它只是使用 @Advice.AllArguments。是否也很容易从建议的方法中捕获返回数据?我的目标不是简单地修改方法,只是“了解进来的内容和出现的内容”。并将其写入文件。返回类型主要是来自javax的响应,但有时是原语。

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) {


  }
}

1 个答案:

答案 0 :(得分:1)

正如Advice类的javadoc中提到的那样:

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