Guice: How do I get an instance of a TypeLiteral-wrapped generic?

user655145 picture user655145 · Jun 22, 2011 · Viewed 12.2k times · Source

I have a generic database access class, which i'm binding using the TypeLiteral construct. Now in a test i want to mock that class and i have therefor created a Provider, that creates a mock instance. In my test, i want to access that mock to define its behaviour. Now the question is, how can i retrieve the object from the injector?

That's my binding definition:

binder.bind(new TypeLiteral<GenericDbClass<Integer>>(){}).GenericDbClassProvider.class);

Normally i would get an instance like this:

injector.getInstance(GenericDbClass.class);

But since i'm not binding the implementation of GenericDbClass to the Interface itself, i don't know how to do that. Do I think to complicated?

Any ideas/help is greatly appreciated!

Answer

jacobm picture jacobm · Jun 22, 2011

Use Guice's Key facility, which is made for exactly this kind of problem. In your case

injector.getInstance(Key.get(new TypeLiteral<GenericDbClass<Integer>>(){});

will do the trick.