考虑这个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
在我看来,两次提供“部分”一次多余,一次作为通用类型,并且还提供它的类.我认为这是不可能的,但是有没有实现HashMapSafe,(保持相同的功能)所以它可以像这样使用?
Map<String,Section>();
或者像这样?:
Map<String,Section> sections = new HashMapSafe<String>(Section.class);
解决方法
正如其他人已经指出的那样,由于类型擦除,你无法改善构造函数的使用,但是你应该能够通过使用静态工厂方法而不是构造函数来提高详细程度……
我不是在编译器前面,我在第一次尝试时永远无法获得方法类型参数,但它会像这样……
public static <K,V> Map<K,V> create( Class<V> cl )
{
return new HashMapSafe<K,V>(cl);
}
...
Map<String,Section> sections = HashMapSafe.create(Section.class);