【问题标题】:How to find method name from within that method in Java? [duplicate]如何从 Java 中的该方法中查找方法名称? [复制]
【发布时间】:2011-06-06 04:57:42
【问题描述】:

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

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

【问题讨论】:

  • 这确实不是您的代码所需要的。我非常建议重新考虑你的设计,这样你就不需要它了。
  • 如果你在那个方法中你已经知道名字了,对吧? :) 如果您想知道调用者方法的名称,下面 Jigar 的答案就是您要查找的答案。只需使用 1 而不是 0 作为索引。

标签: java methods


【解决方案1】:

从 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
     }
   }

【讨论】:

  • 这是一个更好的解决方案,因为您不必创建异常来获取堆栈。
  • 不知道为什么这对我不起作用...它为我打印出“getStackTrace” - 使用 Java 1.5
  • @Zack Macomber,输出是什么:StackTraceElement [] ste = Thread.currentThread().getStackTrace(); for (StackTraceElement s : ste) { System.out.println(s); },您使用的是 Sun JRE 吗?
  • @RealHowTo - 我能够使用 '[2]' 而不是 '[1]' 来获取方法名称 - 我使用 IBM 的 RSA,所以我想我可能使用的是 IBM 的 Java 版本
  • 我正在尝试在 android 活动方法中打印方法名称。我不得不使用Thread.currentThread().getStackTrace()[2].getMethodName()
【解决方案2】:
Method lastMethodCalled = this.getClass().getEnclosingMethod();

【讨论】:

【解决方案3】:
System.out.println(new Exception().getStackTrace()[0].getMethodName());

另见

【讨论】:

  • 使用GetStacktrace()[1] 获取调用方法名。更有用一点:)
  • @Daniel,这是要求的吗?请注意,1) 没有保证堆栈跟踪是准确的,并且 2) 这以前是一个非常昂贵的操作。在最近的 JVM 中应该会更好。
  • 真的吗?什么时候可能会出现不准确的堆栈跟踪?或者它只是不能保证你得到一个?我从来没有遇到过这些问题。
  • 它认为重要的是要明确该解决方案仅适用于 JDK >= 1.4。对于 JDK >= 1.5,您不必每次都实例化一个新的 Exception,这样可以节省资源(查看上面的 RealHowTo 的答案)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 2021-12-19
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
相关资源
最近更新 更多