谁能解释为什么下面这段代码可以编译?
List<Long> longNums = new ArrayList(Arrays.asList("one", "two", "three"));
是因为类型删除吗?
如果我有以下方法:
public <T> T readProperty(String propName, Class<T> type);
我怎样才能确保它会返回,比如说 List<Long>
而不是 List<String>
?显然,在调用方法的类型中,我只能提供 List.class
并祈祷。
//run and pray
List<Long> longNums = readProperty("prop", List.class);
我已经发生过这种方法错误地将一个 String 对象列表分配给一个长数字列表,直到我运行它,我才看到 ClassCastException
.
最佳答案
您不应该期望程序能够正确运行,因为您没有正确使用泛型。
首先,你不应该将 Generics 与 Raws 混在一起,这意味着这个声明
List<Long> longNums = new ArrayList(Arrays.asList("one", "two", "three"));
无效(就正确性而言)。如果是:
List<Long> longNums = new ArrayList<Long>(Arrays.asList("one", "two", "three"));
它甚至不会编译,你会在编译时得到错误(而不是在运行时,这可能更令人困惑和可怕)。
因此,为了进行编译,您的列表应定义为:
List<String> longNums = new ArrayList<>(Arrays.asList("one", "two", "three"));
另外,关于这个声明
//run and pray
List<Long> longNums = readProperty("prop", List.class);
实际上没有办法确定 readProperty
将返回 List<Long>
,因此您必须进行转换或添加 @SuppressWarnings
注解。原因是编译器的类型删除功能——参数化类型 Long
被删除并在运行时消失(当实际执行 readProperty()
并且通过反射获得 prob
的值时)。
关于java - 对 Java 中的泛型感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31853840/