Check if an object is instance of List of given class name

lviggiani picture lviggiani · Jul 28, 2014 · Viewed 55.1k times · Source

Given an Object o and a String className = "org.foo.Foo", I want to check if o is instance of List<className>

I tried this but won't compile:

Class<?> cls = Class.forName(className);
if (o instanceof List<cls>){ // this gives error: cls cannot be resolved to a type
  doSomething();
}

Please note that my inputs are Object o and String className (please mind types).

Answer

Konstantin Yovkov picture Konstantin Yovkov · Jul 28, 2014

It's because of Type Erasure. The statement

if (o instanceof List<cls>) {
  doSomething();
}

will be executed at runtime, when the generic type of the list will be erased. Therefore, there's no point of checking for instanceof generic-type.