【问题标题】:How can I get the class and the method that call to a static method? [duplicate]如何获取调用静态方法的类和方法? [复制]
【发布时间】:2012-01-28 10:54:23
【问题描述】:

我有class X,其中有一个名为doStuff()static 方法,我还有其他几个类,它们的方法出于某种原因调用doStuff()。有没有办法例如在doStuff() 中有一个打印方法来打印它被调用的方法和类?

【问题讨论】:

  • 请不要这样做! (调试可能除外,但即使有测试可能会更好。)

标签: java


【解决方案1】:

是:new Throwable().getStackTrace() 返回StackTraceElement 的数组。索引号 1 是您的来电者。

【讨论】:

  • +1:或Thread.currentThread().getStackTrace()
  • 谢谢,但我使用的索引是 3。索引 1 给了我类 A 和 doStuff() 的名称。
【解决方案2】:
/**
 * <li> 0 dumpThreads
 * <li> 1 getStackTrace
 * <li> 2 getCallingMethodName
 * <li> 3 [calling method]
 * 
 * @return
 */
private String getCallingMethodName() {
    return Thread.currentThread().getStackTrace()[3].getMethodName();
}

【讨论】:

    【解决方案3】:

    您可以使用以下方法获取调用者类:

    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”

    【讨论】:

      【解决方案4】:

      您无需强制Exception 即可执行此操作。检查这个类似的问题:

      Is there a way to dump a stack trace without throwing an exception in java?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-05
        • 1970-01-01
        • 2023-03-26
        • 2011-04-20
        • 1970-01-01
        • 2017-03-02
        相关资源
        最近更新 更多