why instanceof does not work with Generic?

Subhrajyoti Majumder picture Subhrajyoti Majumder · Jan 9, 2013 · Viewed 45.4k times · Source

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. :)

Answer

Jim Garrison picture Jim Garrison · Jan 9, 2013

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.