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

lviggiani :

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

lviggiani :

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.

edited at
0

Comments

0 comments
Login to comment

Related

Check if an object is of a class given the class name in string?

Check if some object is instance of some class in a list

Check if Object is an instance of a class from a list of classes and cast

Check if object is in list given by pyshark

Check if object is a 'direct instance' of a class

Check if class implements interface given the class name

Check whether Swift object is an instance of a given metatype

Check if there is an instance of a class in a list in python

Check if a object is a instance of a class (but not a instance of its subclass)

check in php if a object is a instance of a class but not a instance of a subclass

FreeMarker check the class name of an object

Check if object is instance of any 'number' class?

JavaScript check if object is an instance of current class

Check that a variable is an instance of a Class Object in WooCommerce

Check if Calling Object is Instance of Child Class

Check that object is not instance of any class in typescript

Jest and Typescript: Unable to check if object is instance of class

Coffeescript create new instance of a class given an object of that class

Retrieve Class Name/Instance from Object

Is there a way to get an object instance name inside a class?

Python - Adding class instance name to a list

Ruby - How to find class name given an instance variable?

How to access a Scala object instance given it's full qualified name?

Check the class name of the reference holding an object in Java

List to .json and to list with object class name

How to check if aspecified object exists in a given list of object or not with java

How to check if a name exists in Rcpp List object?

How to check if an HTMLCollection contains an element with a given class name using javascript?

Check if a class has a method with a given name but any signature