3

Is there any slick way (if any) for Guice to somehow bind a class type to an interface? I don't mean an instance of the class, but the actual java.lang.class type itself.

i.e. (obviously doesn't work, but tells what I'm after):

bind(MyInterface.class).to(Class<MyImplementation>)

I know it doesn't seem possible on the outset, but I didn't know if there were any tricks I could take to do this. One that comes to mind would be wrapping the class type in an actual instantiated object or something, but that seems like a last resort.

Any ideas would be greatly appreciated. Thanks!

  • Your question is not very clear for me. What do you want to inject ? May be you could tell us more about the use case. Give us an SSCCE, the `class`, `interface` source code and also the class which depends on. – gontard Jul 11 '14 at 08:27

2 Answers2

6

I figured it out after RTFM. I just missed the existence of the "toInstance" method:

bind(new TypeLiteral(Class<? extends MyInterface>)(){}).toInstance(MyImplementation.class)

Hopefully this helps someone else who runs into a similar issue!

2

It sounds like you just want to do a normal binding

bind(MyInterface.class).to(MyImplementation.class)
Isaiah van der Elst
  • 1,435
  • 9
  • 14
  • Thanks. I was actually looking to bind to get the actual class as opposed to an instance of it. I figured it out and left the answer below. – user3828162 Jul 11 '14 at 19:38