Retrieve the caller instance (not class) of a method or constructor

感情迁移 提交于 2019-12-01 16:17:12

问题


Is it possible to retrieve the caller instance of a method/constructor?

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
    }
}

回答1:


Your gut feeling is right - it's not possible. Personally I think that's a good thing, as it would make code pretty fragile with respect to refactoring (imagine pulling some code out into a static method - suddenly there's no caller object at all).

If you want to express some sort of owner relationship, you should provide that owner explicitly.



来源:https://stackoverflow.com/questions/6580677/retrieve-the-caller-instance-not-class-of-a-method-or-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!