Triton Man Triton Man - 1 year ago 89
Java Question

how to instanceof List<MyType>?

How can I get this sort of thing to work? I can check if

(obj instanceof List<?>)
but not if
(obj instanceof List<MyType>)
. Is there a way this can be done?

Answer Source

That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:

public class GenericList <T> extends ArrayList<T>
     private Class<T> genericType;

     public GenericList(Class<T> c)
          this.genericType = c;

     public Class<T> getGenericType()
          return genericType;