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

ε祈祈猫儿з 提交于 2019-12-04 14:53:00
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!