Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to check if a Field is of type java.util.Collection

I have a utility method that goes through various classes and recursively retrieves the fields. I want to check if that field is a Collection. Here is some sample code:

void myMethod(Class<?> classToCheck)  Field[] fields = classToCheck.getDeclaredFields();  for(Field field:fields) {    // check if field if a Collection<?>  } 

Thanks in advance for the help.

like image 959
Quantum_Entanglement Avatar asked Dec 07 '11 22:12

Quantum_Entanglement


People also ask

How do you check if an object is a collection type in Java?

You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.

How do I know what type of field?

getType() The getType() method of the Field class is used to get the type of field defined by the Field object. The return value helps us in identifying the type of the field.

How do I check if an object is collected?

Contains(T) method is used to determine whether an element is in the Collection<T>. Syntax: public bool Contains (T item); Here, item is the object to locate in the Collection<T>.

How do I check if an object has a specific property in Java?

The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result.


1 Answers

if (Collection.class.isAssignableFrom(field.getType())) {  } 
like image 120
Bozho Avatar answered Sep 22 '22 03:09

Bozho