【问题标题】:Can I determine who is calling a function or instantiating a class in Java? [duplicate]我可以确定谁在调用函数或在 Java 中实例化一个类吗? [复制]
【发布时间】:2011-04-23 21:45:21
【问题描述】:

可能重复:
In Java, how do i find the caller of a method using stacktrace or reflection?

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

【问题讨论】:

  • 谢谢你的答案。由于重复,我也可以关闭线程。

标签: java language-features


【解决方案1】:

你可以使用“假异常”来做到这一点,尽管这个技巧感觉有点脏。

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

getStackTrace 返回一个由StackTraceElement 对象组成的数组,您可以查看API 以了解您可以使用它们做什么。

【讨论】:

  • 不用扔了,看我的回答
  • @org.life.java 谢谢,很高兴知道
【解决方案2】:
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)");
    }
}

【讨论】:

  • 我认为你甚至不需要调用fillInStackTrace:根据docs,构造函数会为你调用它。
猜你喜欢
  • 2012-10-24
  • 2010-12-07
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2020-11-21
相关资源
最近更新 更多