Inject a Class<T> with GIN

有些话、适合烂在心里 提交于 2019-12-12 17:03:51

问题


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


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/7093274/inject-a-classt-with-gin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!