为什么instanceof不能用于Generic? [英] why instanceof does not work with Generic?
问题描述
可能存在重复:
Java:Instanceof和Generics
我想写一个函数它将一个通用列表转换为特定类型列表。找到下面的代码
I am trying to write a function which cast a generic List to specific type List. Find the code below
public <T>List<T> castCollection(List srcList, Class<T> clas){
List<T> list =new ArrayList<T>();
for (Object obj : srcList) {
if(obj instanceof T){
...
}
}
return list;
}
但是 obj instanceof T
显示编译错误 -
But obj instanceof T
showing a compilation error -
无法对类型参数T执行instanceof检查,而是使用它的擦除Object>,因为更多的泛型类型信息会
Cannot perform instanceof check against type parameter T. Use instead its erasure Object >instead since further generic type information will be erased at runtime.
获得理想结果的任何澄清或方法?
any clarification or way to get the desired result?
预先感谢。 :)
推荐答案
你不能这样做。幸运的是,您已经拥有了一个 Class
参数,而不是
You cannot do it this way. Fortunately, you already have a Class<T>
argument so instead do
myClass.isAssignableFrom(obj.getClass())
如果 obj
是类 myClass
或子类。
正如@ILMTitan指出的谢谢),您需要检查 obj == null
以避免潜在的NullPointerException异常,或者使用 myClass.isInstance(obj)
代替。或者做你所需要的。
As @ILMTitan pointed out (thanks), you will need to check for obj == null
to avoid a potential NullPointerException, or use myClass.isInstance(obj)
instead. Either does what you need.
这篇关于为什么instanceof不能用于Generic?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!