【发布时间】:2012-01-28 10:54:23
【问题描述】:
我有class X,其中有一个名为doStuff() 的static 方法,我还有其他几个类,它们的方法出于某种原因调用doStuff()。有没有办法例如在doStuff() 中有一个打印方法来打印它被调用的方法和类?
【问题讨论】:
-
请不要这样做! (调试可能除外,但即使有测试可能会更好。)
标签: java
我有class X,其中有一个名为doStuff() 的static 方法,我还有其他几个类,它们的方法出于某种原因调用doStuff()。有没有办法例如在doStuff() 中有一个打印方法来打印它被调用的方法和类?
【问题讨论】:
标签: java
是:new Throwable().getStackTrace() 返回StackTraceElement 的数组。索引号 1 是您的来电者。
【讨论】:
Thread.currentThread().getStackTrace()
/**
* <li> 0 dumpThreads
* <li> 1 getStackTrace
* <li> 2 getCallingMethodName
* <li> 3 [calling method]
*
* @return
*/
private String getCallingMethodName() {
return Thread.currentThread().getStackTrace()[3].getMethodName();
}
【讨论】:
您可以使用以下方法获取调用者类:
package test;
class TestCaller {
public static void meth() {
System.out.println("Called by class: " + sun.reflect.Reflection.getCallerClass(2));
}
}
public class Main {
public static void main(String[] args) {
TestCaller.meth();
}
}
输出:“由类调用:类 test.Main”
【讨论】:
您无需强制Exception 即可执行此操作。检查这个类似的问题:
Is there a way to dump a stack trace without throwing an exception in java?
【讨论】: