injector.getInstance of a generic type

class, dependency-injection, generics, guice, java

Solution

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

Problem

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?

Original source

Related problems