How to initialize a circular dependency (final fields referencing each other)?

dependency-injection, design-patterns, guice, java, reflection

Solution

You could use a factory method

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

Problem

How do you initialize this: ``` class A { final B b; A(B b) { this.b = b; } } class B { final A a; B(A a) { this.a = a; } } ``` DI framework, reflection, better design? Motivation and a use case (added): My particular use case is simplifying field access in `A`'s and `B`'s sub-classes. So I'm injecting them to shortly reference them by fields in the derived classes without a need to declare explicitly in each sub-class. There is also a recommendation on DI that objects should better be immutable: Guice best practices and anti-patterns.

Original source

Related problems