Suppose I have 5 classes A, B, C, D, E that implement the common interface X. Each of the classes B, C, D, and E has a field of type X (therefore, they can be thought of as shell classes).
Which instances are created is determined at runtime, so I could have, for example, one of the following object graphs:
E -> D -> C -> B -> A D -> B -> A E -> A A
(The order is fixed and the innermost instance is always of type A, but otherwise there are no restrictions.)
No. I would like to create these objects using Guice to avoid providing all other dependencies manually.
What is the easiest way to do this? Currently it seems that I should
- Let Guice instantiate A
- create a module that binds X.class to this instance and a child injector to this add-on module
- Let Guice create the next instance (e.g. type B)
- repeat 2., now binding X.class to instance B
- repeat 3. and 4. until all objects are created.
Is there an easier way? Can I somehow automatically register a new instance of subclass X as a binding for X every time it is created?
Edit: Clarification: "What instances are created at runtime":
My current code is as follows:
X createX() { X x = new A(dependencies); if (useB) x = new B(x, some, dependencies); if (useC) x = new C(x, further, dependencies); if (useD) x = new D(x, dependency); if (useE) x = new E(x, yet, other, dependencies); return x; }
The value of the flags useB, useC, useD and useE comes from the properties file.
My main goal is to keep all the dependencies on the designers manually.
Edit: Solution:
I added my own solution, which I found in the meantime. Thanks to all the defendants!
To improve my solution, you could remove the @InInstance annotation in the constructor options. I experimented with listener types, but I did not find a way to do this. Hints are welcome.