你如何初始化它:
class A {
final B b;
A(B b) {
this.b = b;
}
}
class B {
final A a;
B(A a) {
this.a = a;
}
}
DI 框架、反射、更好的设计?
动机和用例(已添加):
我的特定用例是简化A
和B
子类中的字段访问。因此,我将它们注入(inject)到派生类中的字段中以快速引用它们,而无需在每个子类中显式声明。
还有关于 DI 的建议,对象最好是不可变的:Guice best practices and anti-patterns .
最佳答案
你可以使用工厂方法
class A {
final B b;
A(B b) {
this.b = b;
}
}
abstract class B {
final A a;
B() {
this.a = constructA();
}
protected abstract A constructA();
}
public class C {
public static void main(String []args){
new B(){
protected A constructA(){
return new A(this);
}
};
}
}
关于java - 如何初始化循环依赖(final 字段相互引用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808342/