问题
Possible Duplicate:
Java: Instanceof and 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;
}
But obj instanceof T
showing a compilation error -
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?
Thanks in advance. :)
回答1:
You cannot do it this way. Fortunately, you already have a Class<T>
argument so instead do
myClass.isAssignableFrom(obj.getClass())
This will return true if obj
is of class myClass
or subclass.
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.
回答2:
Short answer: because a type parameter in Java is something just used by the compiler to grant type safety.
At runtime, type information about generic types is discarded because of type erasure but instanceof
is a runtime check that needs a concrete type (not a type variable) to work.
回答3:
T
is a parameterized type and exists for compilation purposes. It does not exist at runtime because of type erasure.
Therefore, obj instanceof T
is not legal.
回答4:
Because java uses erasure, generic types can not be used to check against.
To get the desired result, use Class.isInstance()
.
回答5:
Generic types will be erased after compilation (generics are for compile time type safety) and will be replaced with most applicable type after compilation.
If you want make this compile, replace T with concrete type, example
obj instance String
来源:https://stackoverflow.com/questions/14228637/why-instanceof-does-not-work-with-generic