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

问题描述:

我有class X,在它里面有一个叫做doStuff()static方法,而且我有几个其他的类,其中有些方法因为某些原因调用doStuff()。有没有办法在doStuff()中使用打印方法打印从中调用哪些方法和类?如何获取调用静态方法的类和方法?

+0

请不要”不要这样做! (可能除了调试,但即使那里测试可能会更好。) – 2011-12-27 13:04:21

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

+1

+1:或'Thread.currentThread()。getStackTrace()' – 2011-12-27 12:08:02

+0

谢谢,但我使用的索引是3.索引1给我的名字的A类和doStuff()。 – nyxz 2011-12-27 13:16:22

您不需要强制Exception为了做到这一点。选中此类似的问题:

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

输出:

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

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

可以使用获得致电类 “的类调用:类test.Main”