开发者

Can I determine who is calling a function or instantiating a class in Java? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

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

I'm just curious. I was requesting that feature sometimes, but then I solved it w开发者_如何学Cith more code. (the calling class said its name while calling the method)


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

OR

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


You can do it using 'fake exception', even though this trick feels kinda dirty.

    try {
        throw new RuntimeException();
    } catch (RuntimeException e) {
        System.out.println(e.getStackTrace()[1]);
    }

getStackTrace returns an array of StackTraceElement objects, you can check API to see what you can do with them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜