是否可以检索方法/构造函数的调用者实例?
这个问题已经发布了,但每次的答案都在谈论调用者类(使用堆栈跟踪)而不是调用者实例。 如果存在解决方案,构建对象图(具有通用父类(super class)型)并使用默认构造函数处理父子导航会非常方便。
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
}
}
最佳答案
您的直觉是正确的 - 这是不可能的。我个人认为这是一件好的事情,因为它会使代码在重构方面变得非常脆弱(想象一下将一些代码拉出到一个静态方法中——突然之间根本就没有调用者对象了)。
如果您想表达某种所有者关系,您应该明确提供该所有者。
关于java - 检索方法或构造函数的调用者实例(不是类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6580677/