能否检索一个方法/施工者的打电话?
This question has already been posted, but each time the answers are talking about caller Class (using stacktrace) and not caller instance. If a solution exists, it can be really convenient to build object graph (with a common super type) and handle parent child navigation with default constructor.
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
}
}