如何在Java中从该方法中查找方法名称?

时间:2011-01-09 20:20:59

标签: java methods

我想知道是否有办法知道在运行时正在执行的方法名称?

例如,在private void doSomething (String s)方法中,我想知道我正在执行doSomething (String s)方法。

3 个答案:

答案 0 :(得分:61)

自JDK1.5起,您不需要Exception来获取StackTrace,
你可以使用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
     }
   }

答案 1 :(得分:10)

System.out.println(new Exception().getStackTrace()[0].getMethodName());

另见

答案 2 :(得分:-2)

Method lastMethodCalled = this.getClass().getEnclosingMethod();
相关问题