检索方法或构造函数的调用者实例(不是类)

发布于 2024-11-18 15:18:16 字数 766 浏览 8 评论 0原文

是否可以检索方法/构造函数的调用者实例?

这个问题已经发布,但每次答案都在谈论调用者类(使用堆栈跟踪)而不是调用者实例。 如果存在解决方案,那么构建对象图(具有公共超类型)并使用默认构造函数处理父子导航会非常方便。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人接听 2024-11-25 15:18:16

你的直觉是对的——这是不可能的。我个人认为这是一件好事,因为它会使代码在重构方面变得非常脆弱(想象一下将一些代码拉出到静态方法中 - 突然根本没有调用者对象)。

如果您想表达某种所有者关系,则应明确提供该所有者。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文