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

2019-04-18 17:59发布

问题:

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.

回答1:

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

}


回答2:

You should use Class.isAssignableFrom:

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


回答3:

Using the getType() method

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


回答4:

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


回答5:

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.



回答6:

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.