【发布时间】:2011-07-28 11:50:27
【问题描述】:
考虑这个 HashMap 扩展(如果为 null,则在调用“get”时生成 V 类的实例)
public class HashMapSafe<K, V> extends HashMap<K, V> implements Map<K, V>{
private Class<V> dataType;
public HashMapSafe(Class<V> clazz){
dataType = clazz;
}
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
if(!containsKey(key)){
try {
put((K)key, dataType.newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.get(key);
}
}
它的用法是这样的
Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class);
sections.get(sectionName); //always returns a Section instance, existing or new
在我看来,两次提供“Section”似乎有点多余,一次作为泛型类型,同时提供它的类。我认为这是不可能的,但是有没有实现 HashMapSafe,(保持相同的功能)所以它可以像这样使用?
Map<String,Section> sections = new HashMapSafe<String,Section>();
还是这样?:
Map<String,Section> sections = new HashMapSafe<String>(Section.class);
【问题讨论】:
-
因此,谷歌搜索“java newInstance generic class”发现了几篇涉及 this.getClass() 的旧帖子,随后能够访问对象的泛型,从而获得这些泛型的类,建议您的第一个选项是可能的。见:stackoverflow.com/questions/75175/…