参见英文答案 >
Retrieve the caller instance (not class) of a method or constructor 1个
是否有可能获得调用类的实例对象?
class A{
void foo(){
Object o = getCaller(); //?? expect instance of B
long val1 = .. // get val1 of o via reflection
// do something where val1 is crucial
}
}
class B{
double val1 = Math.random();
public static void main(String[] args) {
new B().callFoo();
}
void callFoo(){
new A().foo();
}
}
我知道我可以通过stacktrace找出调用类/方法但我需要conrete实例来访问实例变量(例如示例中的val1).
我知道它很脏但B类是在一个不可加工的库中,因此几乎不可能在不重建所有内容的情况下通过所需的字段.