3

Is there a way to inject a class type Class<T> in gin? I can't seem to get it working, for example:

class GenericFoo<T> {

  private final Class<T> klass;

  @Inject
  public GenericFoo(Class<T> klass) {
    this.klass = klass;
  }
}

class Bar { }

with an instance injected somewhere:

..
@Inject
GenericFoo<Bar> instance;
..

and a GinModule containing something along the lines of:

bind(new TypeLiteral<Class<Bar>>() {}).to(Bar.class);

Thanks

ryan
  • 31
  • 2

2 Answers2

3

It's not possible. Reflection is forbidden on the client side, so GIN for dependency injection is using deffered binding. It means that during the compilation, GWT generates target implementations which are unknow in your case.

kospiotr
  • 1,837
  • 2
  • 18
  • 29
  • I'm sorry, I think you misunderstood me, made an edit to clarify. I don't need reflection, just want to bind Class to Foo.getClass(). – ryan Aug 17 '11 at 15:12
3

If this were regular Guice (as opposed to Gin), you could do:

bind(new TypeLiteral<Class<Bar>>(){}).toInstance(Bar.class);

But Gin doesn't support .toInstance(...) bindings. Instead, you should be able to use a Provider or an @Provides method, like:

@Provides
Class<Bar> providesBarClass() {
  return Bar.class;
}
Andrew McNamee
  • 1,705
  • 1
  • 13
  • 11