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.
if (Collection.class.isAssignableFrom(field.getType())) {
}
You should use Class.isAssignableFrom
:
if (Collection.class.isAssignableFrom(field.getType())
...
Using the getType()
method
Field field = ...;
if ( Collection.class.isAssignableFrom( field.getType() ) ){
//do something with your collection
}
//This execute if
List<String> cashType = split(" ,AlL ");
if(cashType instanceof Collection){
System.out.println("cashType instanceof Collection");
}else{
System.out.println("cashType is not instanceof Collection");
}
//This executes else
List<String> cashType = split(" ,AlL ");
if(cashType instanceof Hashtable){
System.out.println("cashType instanceof Collection");
}else{
System.out.println("cashType is not instanceof Collection");
}
You can use getType()
in the following way:
if (field.getType().equals(Collection.class) {
// Do something
}
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 as List
or Vector
.
for(Field field:fields) { // check if field if a Collection
Object myInstance = field.get(classInstance);
// where classInstance is the instance in which the fields is stored
if(myInstance instanceof Collection) {
//Do your thing
}
}
This 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.