how to instanceof List<MyType>?

Rocky Pulley picture Rocky Pulley · Apr 11, 2012 · Viewed 122.9k times · Source

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

Martijn Courteaux picture Martijn Courteaux · Apr 11, 2012

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;
     }
}