java 动态判断List(泛型类)的具体类型

阅读更多
package test;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;


public class test {

    public static void main(String[] args) {

        Class dtoClass = person.class;
        Field[]  fields = dtoClass.getDeclaredFields();
        for (Field field : fields ) {
            judgeFieldType(field);
        }
    }

    private static void judgeFieldType(Field field) {
        String name = field.getName();

        if (field.getGenericType() instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) field.getGenericType();

           //判断具体类的类型

             if (pt.getRawType().equals(List.class)) {

           // 判断泛型类的类型
                if (pt.getActualTypeArguments()[0].equals(String.class)) {
                    System.out.println(name + " is List;");
                } else if (pt.getActualTypeArguments()[0].equals(int.class)
                        || pt.getActualTypeArguments()[0].equals(Integer.class)) {
                    System.out.println(name + " is List;");
                }
            }
        }else if (field.getGenericType().equals(String.class)) {
            System.out.println(name + " is String;");
        } else if (field.getGenericType().equals(int.class) || field.getGenericType().equals(Integer.class)) {
            System.out.println(name + " is int;");
        }
    }

}
package test;

import java.util.List;


public class person {

public String name;
public int age;
public List cord;
public List meter;

}

你可能感兴趣的:(java,泛型)