我正在编写一个用于调试和度量捕获的方法,这样:
void capture(Object value, String debugName) {
System.out.println("captured " + debugName + " with value " + value);
}
并使用:
调用它capture(foo.bar(), "foo.bar");
是否有任何方法可以直接获得值表达式字符串,所以我不需要传递debugName?比如:
void capture(Object value) {
System.out.println("captured " + getStack(value) + " with value " + value);
}
你可以使用堆栈来找出关于foo.bar()
调用的东西的唯一方法是从bar()
方法本身中运行capture()
代码,即一些AOP框架或一些基于java.lang.reflect.Proxy
的方法将你的代码注入bar()
本身。
在你的例子中,capture()
的堆栈永远不会暗示foo.bar()
,而是任何称为capture
的方法。如果您让foo.bar()
调用它,您可以从Thread.currentThread().getStackTrace()[1]
获得TypeOfFoo.bar()
的信息。
但是,没有办法找出名称foo
(在您的示例中),因此您必须使用captured TypeOfFoo.bar() with value ...
您可以记录capture
被调用的位置:
public class Test {
public static void capture(Object value) {
Exception e = new Exception();
System.out.println("captured value " + value + " at " + e.getStackTrace()[1]);
}
public static void someFunc() {
capture("alice");
}
public static void main(String[] args) {
capture("fred");
someFunc();
}
}
打印:
captured value fred at Test.main(Test.java:25)
captured value alice at Test.someFunc(Test.java:21)