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).
Ok, I found a method... it's a little dirty code but it works:
if (o instanceof List<?>){
ParameterizedType pt = (ParameterizedType)o.getClass().getGenericSuperclass();
String innerClass = pt.getActualTypeArguments()[0].toString().replace("class ", "");
System.out.println(innerClass.equals(className)); // true
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments