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).
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.
The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).
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.
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.
I think you can do it in two steps: First, you check it's a List.
if (o instanceof List)
Then, you check that one (each?) member of the list has the given type.
for (Object obj : (List) o) {
if (obj instanceof cls) {
doSomething();
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With