我想知道是否有办法知道在运行时正在执行的方法名称?如何在Java中使用该方法查找方法名称?
例如,private void doSomething (String s)
方法里面,我想知道我执行doSomething (String s)
方法。
我想知道是否有办法知道在运行时正在执行的方法名称?如何在Java中使用该方法查找方法名称?
例如,private void doSomething (String s)
方法里面,我想知道我执行doSomething (String s)
方法。
由于JDK1.5,你不需要一个例外,以获得堆栈跟踪,
你可以用Thread.currentThread().getStackTrace()
得到它:
public class Test2 {
public static void main(String args[]) {
new Test2().doit();
}
public void doit() {
System.out.println(
Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit
}
}
System.out.println(new Exception().getStackTrace()[0].getMethodName());
请参见
Method lastMethodCalled = this.getClass().getEnclosingMethod();
这真的不是你的代码应该要求的东西。我非常建议重新考虑你的设计,这样你就不需要它了。 – 2011-01-09 20:28:04
如果你在这个方法里面,你已经知道这个名字了,对吧? :)如果你想知道调用方法的名字,Jigar的答案就是你正在寻找的。只需使用1而不是0作为索引。 – 2011-01-09 20:28:35