Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create recursive object graphs with Guice?
    primarykey
    data
    text
    <p>Suppose I have 5 classes A, B, C, D, E that all implement a common interface X. Each of the classes B, C, D and E has a field of type X (so they can be seen as wrapper classes).</p> <p>Which instances are created is determined at runtime, so I could have for example one of the following object graphs:</p> <pre><code>E -&gt; D -&gt; C -&gt; B -&gt; A D -&gt; B -&gt; A E -&gt; A A </code></pre> <p>(The order is fixed and the innermost instance is always of type A, but otherwise there are no restrictions.)</p> <p>No I'd like to create this objects with Guice to avoid providing all their other dependencies by hand.</p> <p>What's the easiest way to do this? Currently it seems that I have to</p> <ol> <li>let Guice create instance of A</li> <li>create a module that binds X.class to this instance and a child injector with this additional module</li> <li>let Guice create the next instance (e.g., of type B)</li> <li>repeat 2., now binding X.class to the instance of B</li> <li>repeat 3. and 4. until all objects are created</li> </ol> <p>Is there an easier way? Could I perhaps somehow automatically register a new instance of a subclass of X as a binding for X each time it is created?</p> <p><strong>Edit: Clarification of "<em>Which instances are created is determined at runtime</em>":</strong></p> <p>My current code looks like this:</p> <pre><code>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; } </code></pre> <p>The value of the flags useB, useC, useD, and useE comes from a properties file.</p> <p>My main goal is to save providing all the dependencies to the constructors manually.</p> <p><strong>Edit: Solution:</strong></p> <p>I have added my own solution which I have found in the meantime. Thanks to all answerers!</p> <p>A way to improve my solution would be to make it possible to remove the <code>@InInstance</code> annotation on the constructor parameters. I have experimented with type listeners, but I haven't found a way to do this. Hints would be welcome.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload