【发布时间】: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