java使用typeliteral在guice中注入泛型,但typeliteral构造函数受到保护
我已经开始学习guice,并偶然发现使用guice注入泛型类型。网络中的所有解决方案似乎都使用类似new TypeLiteral<Generic<Type>>(){}
的东西。然而,当我尝试这样做时,它显示TypeLiteral
的构造函数受到保护。如何使用TypeLiteral.get()
执行泛型注入?示例代码:
public interface Repository<T> {
void save(T item);
T get(int id);
}
public StringRepository implements Repository<String> {
@Override
public void save(String item) {
// do saving
}
@Override
public String get(int id) {
// get item and return
return item;
}
}
public MyModule extends AbstractModule{
@Override
public void configure() {
....
TypeLiteral<Repository<String>> typeLiteral =
TypeLiteral.get((Repository<String>.class));//does not work
//does not work either because constructor is protected
bind(new TypeLiteral<Repository<String>>(){}).to(StringRepository.class);
}
}
# 1 楼答案
你的文字是
new TypeLiteral<Generic<Type>>(){}
。您的屏幕截图显示new TypeLiteral<Generic<Type>>()
。第一个在末尾有{}
,第二个没有。这些花括号很关键-它们将表达式从创建TypeLiteral
的新实例更改为创建TypeLiteral
的匿名子类并创建该子类的实例这对于处理泛型类型擦除是必要的。为了使
TypeLiteral
发挥作用,它必须在运行时知道泛型类型参数是什么。类型擦除意味着泛型类的简单实例在运行时不知道其类型参数是什么。然而,从泛型类继承的类在运行时确实知道它在继承中使用了什么类型的参数。即: