注入类< T>与GIN [英] Inject a Class<T> with GIN

查看:155
本文介绍了注入类< T>与GIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在杜松子酒中注入类类型 Class< T> ?例如:

  class GenericFoo< T> {

private final Class< T>克拉斯;

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



class Bar {}

注入一个实例:

  .. 
@Inject
GenericFoo< Bar>实例;
..

和包含以下内容的GinModule:

$ (Bar.class); b
$ b

  bind(new TypeLiteral< Class< Bar>>(){})。 

谢谢

解决方案如果这是常规的Guice(而不是杜松子酒),你可以这样做:

  bind(new TypeLiteral<类<酒吧及GT;>(){})toInstance(Bar.class)。 

但是Gin不支持 .toInstance(...) code>绑定。相反,您应该可以使用 Provider @Provides 方法,如:

  @Provides 
Class< Bar> provideBarClass(){
return Bar.class;
}


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

解决方案

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

这篇关于注入类&lt; T&gt;与GIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆