6

I have seen this post about registering generic type.

example on how to register:

 bind(new TypeLiteral<Dal<RoutingResponse>>() {}).to((Class<? extends Dal<RoutingResponse>>) ResponseDal.class);

however how can I get an instance of a generic type from the injector?

I have tried:

injector.getInstance(Dal<RoutingResponse>().getClass());

but got compilation error.

How should I write this?

Community
  • 1
  • 1
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

1 Answers1

17

You can use Key to get instances of these bindings:

injector.getInstance(new Key<Dal<RoutingResponse>>() {}); // supplied by @DanielPryden in the comments

or in a longer version, with a TypeLiteral:

injector.getInstance(Key.get(new TypeLiteral<Dal<RoutingResponse>>() {}));
Bombe
  • 81,643
  • 20
  • 123
  • 127
condit
  • 10,852
  • 2
  • 41
  • 60
  • 1
    Or just use `Key` directly: `new Key>() {}` will do the same thing and is shorter. – Daniel Pryden Feb 19 '15 at 20:43
  • Hi I am trying to do something similar, but my generic class has another dep which is injected. For now I have to fetch the dependency and put it in the constructor, is there a way to avoid that? Code example - `Dep dep = injector.getInstance(Dep.class); injector.getInstance(Key.get(new TypeLiteral>(dep) {}));` can I simply write it like `injector.getInstance(Key.get(new TypeLiteral>(dep) {}));` and let guice handle the DI of dep? – Manthan Jamdagni Apr 08 '19 at 12:04