【问题标题】:Find the caller of a method (reflection) in Java [duplicate]在Java中查找方法(反射)的调用者[重复]
【发布时间】:2014-02-08 17:50:55
【问题描述】:

我想在 Java 中恢复调用者的实例。 这是我的代码

class A {
    void methodA() {
        B b = new B();
        A a = b.methodB(); //needs to be the same instance ie "this"
    }
}

class B {
    A methodB() {
        //Here the code (with reflection) I need
        A a = getPreviousInstanceCaller();
        return A
    }
}

Java 中是否存在这样做的方法?也许有反射?

【问题讨论】:

  • 如果该方法是从static 方法调用的呢?查看StackTraceElement 类。您可以找到调用它的类,但不一定涉及实例。
  • 您可以检查堆栈跟踪并获取第一个“跃点”中的元素。据我所知,没有其他解决方案,因为方法调用不是保留的东西(堆栈跟踪除外)。

标签: java reflection


【解决方案1】:

您不需要对此进行反思。您需要其中一种方法。

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace%28%29

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace%28%29

请注意堆栈跟踪元素的顺序(0、1、2 等)
JDK 的不同版本可能会有所不同。在某些版本中的含义
元素 0 可能是最顶层的元素,而在其他元素中它可能是
最底部的一个。这是一个重要的事情要牢记。

查看这里了解更多详情。

Getting the name of the current executing method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    相关资源
    最近更新 更多