如何获取调用静态方法的类和方法?

时间:2011-12-27 10:55:44

标签: java

我有class X,其中有一个名为static的{​​{1}}方法,我有几个其他类,其方法由于某种原因调用doStuff()。有没有办法让doStuff()中的print方法打印出来的方法和类?

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

/**
 * <li> 0 dumpThreads
 * <li> 1 getStackTrace
 * <li> 2 getCallingMethodName
 * <li> 3 [calling method]
 * 
 * @return
 */
private String getCallingMethodName() {
    return Thread.currentThread().getStackTrace()[3].getMethodName();
}

答案 2 :(得分:1)

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

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();
    }
}

输出:“按类调用:class test.Main”

答案 3 :(得分:0)

为了做到这一点,您不需要强制 Exception。检查这个类似的问题:

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

相关问题