java - 通用方法触发类型安全错误 - 为什么?

标签 java generics

同时研究 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/

相关文章:

java - 使用 Eclipse 在 android 中获取 java.lang.NoClassDefFoundError

java - “Main method not found in class…”但它在那里?那为什么会出错呢?

java - Swing 的 Unicode 支持的限制

shell+java错误

java - 当泛型不是协变时,为什么可以显式转换泛型类型数组?

java - JTextPane 在上一行之后打印文本

c# - 泛型和显式/隐式运算符

java - 为什么我要使用 java.lang.Class.cast

swift - 如何在当前类型 Swift 中使用泛型函数

java - 用 "super"生成