我可以确定谁在调用函数或在Java中实例化一个类吗? [英] Can I determine who is calling a function or instantiating a class in Java?

查看:138
本文介绍了我可以确定谁在调用函数或在Java中实例化一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Java中,如何使用堆栈跟踪或反射找到方法的调用者?

我只是很好奇。我有时会请求该功能,但后来我用更多代码解决了它。 (调用类在调用方法时表示其名称)

I'm just curious. I was requesting that feature sometimes, but then I solved it with 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)");
    }
}

这篇关于我可以确定谁在调用函数或在Java中实例化一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆