如何在Java中从该方法中查找方法名称?
我想知道是否有办法知道在运行时执行的方法名称?
例如,在private void doSomething (String s)
方法中,我想知道我正在执行doSomething (String s)
方法。
从JDK1.5开始,您不需要Exception来获取StackTrace,
你可以用Thread.currentThread().getStackTrace()
来获取它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());
另见
- 可以-I-决定-谁-是呼-A-function或-实例-A-类中的Java
Method lastMethodCalled = this.getClass().getEnclosingMethod();