【发布时间】:2018-04-22 18:47:06
【问题描述】:
简而言之,我正在开发一个系统,该系统能够为您提供有关执行 java 程序所提供的结果的信息。考虑过下面的问题,不知道用java能不能解决。
我有以下课程:
public class ClassA {
ClassB classB= new ClassB();
public Integer method1(){
return classB.method2();
}
}
public class ClassB {
ClassC classC = new ClassC();
public Integer method2() {
return this.classC.method3() + this.classC.method4();
}
}
public class ClassC {
public Integer method3() {
return 3;
}
public Integer method4() {
return 4;
}
}
到目前为止,我可以通过使用动态代理来捕获方法的每次调用。特别是,我使用包 java.lang.reflect 中的 Proxy 和 InvocationHandler 对象。这是我遵循的示例(https://www.concretepage.com/java/dynamic-proxy-with-proxy-and-invocationhandler-in-java)。
我的问题是,如果有人知道我如何提供以下信息: “method1()的返回是由method2()的返回产生的,method2()的返回又是由method3()的返回和method4()的返回产生的”。
【问题讨论】:
-
有一个调试器api和其他相关的低级api。在程序本身运行的运行时中,您可以在内部执行的操作相当有限。
-
如果您可以控制 JVM,另一个选项是检测 (
java.lang.instrumentation)。当你的类被加载时,你可以将代码注入到每个构建调用树的方法中,如果你愿意的话(带有相关的缩进),你会得到类似:method1 -> method2 -> method3,method4。因此,您可以在填充所述调用树的每个方法的开头添加一些代码,并在方法的末尾从树中弹出子项。
标签: java reflection proxy-pattern