Cannot perform instanceof check against parameterized type ArrayList<Foo>

Solution 1:

It means that if you have anything that is parameterized, e.g. List<Foo> fooList = new ArrayList<Foo>();, the Generics information will be erased at runtime. Instead, this is what the JVM will see List fooList = new ArrayList();.

This is called type erasure. The JVM has no parameterized type information of the List (in the example) during runtime.

A fix? Since the JVM has no information of the Parameterized type on runtime, there's no way you can do an instanceof of ArrayList<Foo>. You can "store" the parameterized type explicitly and do a comparison there.

Solution 2:

You could always do this instead

try
{
    if(obj instanceof ArrayList<?>)
    {
        if(((ArrayList<?>)obj).get(0) instanceof MyObject)
        {
            // do stuff
        }
    }
}
catch(NullPointerException e)
{
    e.printStackTrace();
}

Solution 3:

Due to type erasure, the parameterized type of the ArrayList won't be known at runtime. The best you can do with instanceof is to check whether tempVar is an ArrayList (of anything). To do this in a generics-friendly way, use:

((tempVar instanceof ArrayList<?>) ? tempVar : null);