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.
//This execute if
//This executes else
You can use
getType()
in the following way:This will only work if the field is declared as a
Collection
. It will not work if the field is a subtype of Collection, such asList
orVector
.You should use
Class.isAssignableFrom
:Using the
getType()
methodThis tests whether the actual object referred to by the field 'field' (of the object classInstance) implements Collection. If you want to tests whether the declared type of Field implements Collection then that will be different.