Java:组件如何知道其所有者

假设我有一个A类和一个B类。

 public class A { private B b; public A() { this.b = new B(); } public B getB() { return this.b; } } public class B { public String getSome() { return "Get some!"; } } 

我知道我可以通过A获得B,因为A 拥有 (或拥有 )B: new A().getB()
但如果我有B,我可以得到A吗?

当然,只需在类B中添加例程getA() ,并将构造函数中的行更改为

 public A() { this.b = new B(this); } 

这当然假设你的B类有一个接受A的构造函数,例如,

 public B(A a) { this.a = a; } 

B需要明确引用其所有者:

 public class B { private final A owner; public B(A owner) { this.owner = owner; } public A getOwner() { return owner; } } 

A

 public A() { b = new B(this); } 

不。 在Java中没有“所有者”这样的东西。 任何数量的其他对象都可以引用任何对象。

如果你需要B总是绑定到A的实例,那么使B成为A的内部类:

 class A { B b = new B(); class B { String getSome() { // this will refer to the enclosing A return A.this.toString(); } } } 

内部(非静态)类始终具有对封闭实例的隐式引用,没有它就不能存在。 为了从外部实例化B,你需要一个讨厌的语法: B b = new A().new B();

你不能。 B没有提及A.

没有。

类a引用了类B,但类B没有引用类A.引用只是一种方式。

不,那是不可能的。 您正在寻找反向引用,但如果需要,我们必须在代码中创建它们。

如果要收集B的所有引用,可以使用构造函数或创建B的工厂(模式)来执行此操作。 我将展示工厂:

 public class B { private static Set referencers = new HashSet(); private B(){} // no public constructor public static create(Object parent) { // cooperative approach, the caller should pass "this" referencers.add(parent); } public static remove(Object parent) { referencers.remove(parent); } } 

你也可以使用内部类

包装测试;

公共类A {

 B b = null; public B getB() { return b; } public class B { public A getA() { return A.this; } } public static void main(String[] args) { B b = new A().new B(); } 

}