是否可以检索方法/构造函数的调用者实例?
这个问题已经发布,但每次答案都是关于调用者类(使用堆栈跟踪)而不是调用者实例.如果存在解决方案,那么构建对象图(具有公共超类型)并使用默认构造函数处理父子导航可能非常方便.
public class TestCallStack {
public static class BaseClass {
BaseClass owner;
// //ok, this is the correct way to do it
// public BaseClass(BaseClass owner) {
// this.owner = owner;
// }
public BaseClass() {
//this.owner = ???????;
}
}
public static class Parent extends BaseClass {
Child child = new Child();
}
public static class Child extends BaseClass {
}
public static void main(String[] args) {
Parent parent = new Parent();
System.out.println(parent.child.owner==parent); // must be true
} …
Run Code Online (Sandbox Code Playgroud)