Possible Duplicate:
In Java, how do i find the caller of a method using stacktrace or reflection?


我只是好奇。有时我要求该功能,但是后来我用更多的代码解决了。 (调用类在调用方法时说出其名称)

最佳答案

private Class getCallingClass() {
    return new SecurityManager() {
       protected Class[] getClassContext(){return super.getClassContext();}
    }.getClassContext()[2];
}

要么
public class Foo {

    public static final void main(final String[] args) {

        test();
    }

    private static void test() {

        Throwable e = new Throwable();

        StackTraceElement[] elements = e.getStackTrace();
        System.out.println(elements.length > 1 ? elements[1].toString() : "(no caller)");
    }
}

09-25 20:53