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

2019-04-18 18:26发布

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.

6条回答
放荡不羁爱自由
2楼-- · 2019-04-18 18:33

//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");
 }
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-18 18:36

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.

查看更多
Juvenile、少年°
4楼-- · 2019-04-18 18:41
if (Collection.class.isAssignableFrom(field.getType())) {

}
查看更多
The star\"
5楼-- · 2019-04-18 18:42

You should use Class.isAssignableFrom:

if (Collection.class.isAssignableFrom(field.getType())
    ...
查看更多
干净又极端
6楼-- · 2019-04-18 18:43

Using the getType() method

Field field =  ...;
if ( Collection.class.isAssignableFrom( field.getType() ) ){
  //do something with your collection
}
查看更多
【Aperson】
7楼-- · 2019-04-18 18:48
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.

查看更多
登录 后发表回答