Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 243
lviggiani Avatar asked Jul 28 '14 20:07

lviggiani


People also ask

How do you check if an object is an instance of a particular class?

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.

How do you check if an object is an instance of an ArrayList?

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.

How do I check if an object is an instance of a given class or of a subclass of it?

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

How do I find the instance of a list?

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.


3 Answers

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.

like image 147
Konstantin Yovkov Avatar answered Oct 04 '22 04:10

Konstantin Yovkov


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();
    }
}
like image 28
Fabien Fleureau Avatar answered Oct 04 '22 05:10

Fabien Fleureau


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
}
like image 40
lviggiani Avatar answered Oct 04 '22 05:10

lviggiani