user3828162
user3828162

Reputation: 91

Guice - create binding to java.lang.class

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!

Upvotes: 3

Views: 128

Answers (2)

user3828162
user3828162

Reputation: 91

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!

Upvotes: 6

Isaiah van der Elst
Isaiah van der Elst

Reputation: 1445

It sounds like you just want to do a normal binding

bind(MyInterface.class).to(MyImplementation.class)

Upvotes: 2

Related Questions