Java 反射类型:Type
各个方法
1. 得到class的成员变量
首先得到object的class对象
然后在class对象中用getDeclaredFields()方法来获得class的成员变量
FieldTest ft = new FieldTest();
Class ftClass = ft.getClass();
Field[] fields = ftClass.getDeclaredFields();
2. field的函数
Field对象有很多成员方法
getName()获取名称。
getGenericType() 返回一个Type对象
getType() 返回Class对象
getGenericType 和getType区别:
-
返回类型一个是Class对象一个是Type接口。
-
如果属性是泛型,getType()返回属性的接口类型。getGenericType()还能返回参数类型。
String fieldName = field.getName();
Type genericType = field.getGenericType();
boolean isParameterizedType = (genericType instanceof ParameterizedType);
Class fieldClazz = field.getType();
String valueTypeName = genericType.getTypeName();
3.获取范型的Type和Class
获取 范型的key和value的Type
Type[] genericTypes = ((ParameterizedType) genericType).getActualTypeArguments();
Type type0 = genericTypes[0];
Type type1 = genericTypes[1];
通过google的com.google.common.reflect.TypeToken.of(type1).getRawType()方法获取map的key或者value的class类型。
Class<?> clazz = com.google.common.reflect.TypeToken.of(type1).getRawType();
总代码
class FieldTest {
private String pri;
protected String pro;
public Map<Integer, HashMap<Integer, Float>> fcmap;
public FieldTest()