我们编写了一个使用泛型的库,我不确定如何创建泛型类型的实例。那么create方法怎么写呢?
public class Lib<V extends Base> {
private HashMap<Integer, V> map = new HashMap<Integer, V>();
public V get(int key) {
return map.get(key);
}
public void add(int key, V value) {
map.put(key, value);
}
public void create(int key) {
// V v = new V(); // ?? How to implement this line
// add(key++, v);
}
}
最佳答案
从语言的角度来看,不能保证 V
具有非抛出、可访问、无参数的构造函数。处理这种情况的标准方法是引入一个抽象工厂,例如 my answer here .
关于java - 通用类型类启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010131/