Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to instanceof List<MyType>?

Tags:

java

generics

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?

like image 815
Rocky Pulley Avatar asked Apr 11 '12 14:04

Rocky Pulley


4 Answers

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;
     }
}
like image 88
Martijn Courteaux Avatar answered Oct 19 '22 09:10

Martijn Courteaux


if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object
}
like image 29
Sats Avatar answered Oct 19 '22 09:10

Sats


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

like image 9
evanwong Avatar answered Oct 19 '22 10:10

evanwong


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.
    }
}
like image 9
Ivo Stoyanov Avatar answered Oct 19 '22 10:10

Ivo Stoyanov