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?


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

if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object
}

You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List


This could be used if you want to check that object is instance of List<T>, which is not empty:

if(object instanceof List){
    if(((List)object).size()>0 && (((List)object).get(0) instanceof MyObject)){
        // The object is of List<MyObject> and is not empty. Do something with it.
    }
}

    if (list instanceof List && ((List) list).stream()
                                             .noneMatch((o -> !(o instanceof MyType)))) {}