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).
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.