Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>All you need here is a cast to a raw type. As in <a href="https://stackoverflow.com/users/975497/chooks">chooks</a>'s comment below (thank you!), Guice effectively acts like a map from key (often the class object) to value (Provider of that class), and the generics just help to keep the common case sane. If you're sure that your key matches, you can override the generics like this:</p> <pre><code>@Override protected void configure() { for (Object object : getYourListOfInitializedObjects()) { bindObjectAsSingleton(object); } } /** Suppress warnings to convince the Java compiler to allow the cast. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void bindObjectAsSingleton(Object object) { bind((Class) object.getClass()).toInstance(object); } </code></pre> <p>As <a href="https://stackoverflow.com/users/788207/vladimir-matveev">Vladimir</a> mentioned above, this tends not to encourage good Guice design, because even if you have your <code>DependencyImpl</code> implement <code>Dependency</code>, the above will only create a binding to <code>DependencyImpl</code>. Also, all classes in your list of initialized singletons must be created without the benefit of Guice injection themselves, so you're restricting yourself to classes you've initialized externally without Guice's help. You might use the above pattern if you're migrating from a legacy "pile of singletons" into Guice, but you'll probably get farther if you structure your <code>configure</code> method like this as soon as possible:</p> <pre><code>@Override public void configure() { // Let Guice create DependencyOne once, with injection, // immediately on injector creation. bind(DependencyOne.class).asEagerSingleton(); // Let Guice create DependencyTwo once, with injection, // but this way you can hopefully rely on interface DependencyTwo // rather than concrete implementation DependencyTwoImpl. bind(DependencyTwo.class).to(DependencyTwoImpl.class).asEagerSingleton(); // Bind DependencyThree to an instance. Instance bindings are // implicitly singletons, because you haven't told Guice how to // create another one. bind(DependencyThree.class).toInstance(getDependencyThreeInstance()); // ...and so forth for everything in your list. } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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