同时研究 this question 的解决方案,我想出了以下代码,其中有一些编译器警告。一个警告是:
Type safety: The expression of type Test.EntityCollection needs unchecked conversion to conform to Test.EntityCollection<Test.Entity>
我不完全明白为什么会出现这个警告。通过传入 Class<M>
输入并声明该方法返回 EntityCollection<M>
,为什么我没有做足够的工作来说服 (Java 7) 编译器返回正确的类型?
static class Entity {
}
static class EntityCollection<E extends Entity> {
private EntityCollection(HashMap<?, E> map) {
}
public static <T extends HashMap<?, M>, M extends Entity> EntityCollection<M> getInstance(
Class<T> mapType, Class<M> entityType)
throws ReflectiveOperationException {
T map = mapType.getConstructor().newInstance();
return new EntityCollection<M>(map);
}
}
public static void main(String[] args) throws Exception {
// both compiler warnings are on the line below:
EntityCollection<Entity> collection = EntityCollection.getInstance(
LinkedHashMap.class, Entity.class);
}
如果有人可以改进代码以完全避免警告,则加分。我已经盯着它看了一段时间了,还没有想出任何方法来减少警告。
最佳答案
问题是 getInstance
是一个泛型方法,但您不向它传递泛型类型参数。你可以像这样传递它们来绕过它:
public static void main(String[] args) throws Exception {
EntityCollection<Entity> collection = EntityCollection.<LinkedHashMap, Entity>getInstance(
LinkedHashMap.class, Entity.class);
}
您仍然需要处理原始类型警告,因为 LinkedHashMap
是泛型。这在您的情况下是有问题的,因为 key 类型中有一个通配符。
你在这里面临几个问题:
您不能像这样传递参数化类对象:LinkedHashMap<Object, Entity>.class
所以你几乎坚持使用 rawtypes 警告。
关于java - 通用方法触发类型安全错误 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761766/