18

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!

  • As a short term solution i just extended the generic interface with a concrete definition, so i can now get an instance. Still, is there a way to accomplish the task in a more generic way? –  Jun 22 '11 at 12:14

1 Answers1

45

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.

jacobm
  • 13,790
  • 1
  • 25
  • 27
  • 18
    `injector.getInstance(new Key>(){})` will also work if you don't need to provide any binding annotation. – ColinD Jun 22 '11 at 15:12