有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

}

}

Screenshot of my problem


共 (1) 个答案

  1. # 1 楼答案

    你的文字是new TypeLiteral<Generic<Type>>(){}。您的屏幕截图显示new TypeLiteral<Generic<Type>>()。第一个在末尾有{},第二个没有。这些花括号很关键-它们将表达式从创建TypeLiteral的新实例更改为创建TypeLiteral的匿名子类并创建该子类的实例

    这对于处理泛型类型擦除是必要的。为了使TypeLiteral发挥作用,它必须在运行时知道泛型类型参数是什么。类型擦除意味着泛型类的简单实例在运行时不知道其类型参数是什么。然而,从泛型类继承的类在运行时确实知道它在继承中使用了什么类型的参数。即:

    // <String> is erased at run time.
    new ArrayList<String>();
    
    // <String> is preserved at run time, as part of the class's information.
    class MyList extends ArrayList<String> { }
    
    // A class identical to MyList is created, except without the name, and an instance of that class is created.
    new ArrayList<String>(){};