Quantum_Entanglement
Quantum_Entanglement

Reputation: 1633

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.

Upvotes: 29

Views: 43304

Answers (6)

Suresh Arora
Suresh Arora

Reputation: 11

//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");
 }

Upvotes: 1

DJClayworth
DJClayworth

Reputation: 26906

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.

Upvotes: 0

Robin
Robin

Reputation: 36621

Using the getType() method

Field field =  ...;
if ( Collection.class.isAssignableFrom( field.getType() ) ){
  //do something with your collection
}

Upvotes: 3

ampersandre
ampersandre

Reputation: 3216

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.

Upvotes: 0

Bozho
Bozho

Reputation: 597382

if (Collection.class.isAssignableFrom(field.getType())) {

}

Upvotes: 94

Kirk Woll
Kirk Woll

Reputation: 77606

You should use Class.isAssignableFrom:

if (Collection.class.isAssignableFrom(field.getType())
    ...

Upvotes: 8

Related Questions