这个问题在这里已有答案:
到目前为止,我已经看到了一个类似的问题:passing reference of class to another class,他刚刚要求将A类的引用传递给B类。
好吧,我到目前为止只对构造函数做了。
只要我这么简单,我就会这样做。
...
this.classA = new ClassA(classB); //getting the null reference
this.classB = new ClassB(classA); //getting the reference from new ClassA
...
classB将包含null,因为它是在classA之后创建的,表示null引用已经存在。
在A类中创建后是否有另一种方法来访问引用?
说新ClassB的参考?
一个代码示例是惊人的,因为现在我不理解到目前为止我通过创建多个构造函数所听到的“解决方案”...我甚至不确定它们是否有效。
编辑:这就是我的结构
DestinationContentPanel - > DestinationMainPanel - > DestinationHealthMainPanel - > MainPanel < - BottomBarMainPanel < - LeftPanel
这听起来像是你想要避免的设计。但是,如果你必须这样做,我建议创建一个包含对这两个对象的引用的类,并将其传递给classA和classB:
class RefHolder {
ClassA a;
ClassB b;
}
然后使用它:
RefHolder r = new RefHolder();
r.a = new ClassA(r);
r.b = new ClassB(r);
//at this point, both classes can use the RefHolder that was passed
//to the constructors to access instances of ClassA and ClassB
但这只是一种解决方法,我建议不要使用那种循环依赖。