当我们通过Class.getDeclaredFieldName("fieldName")
获取field之后,
我们有两种方式来后期field type:
public class Demo {
@Test
public void test() throws ClassNotFoundException {
Class clazz = Class.forName("Market");
Field[] declaredFields = clazz.getDeclaredFields();
for(int i = 0; i < declaredFields.length; i++){
String name = declaredFields[i].getName();
ParameterizedType genericType = (ParameterizedType)declaredFields[i].getGenericType();
Class<?> type = declaredFields[i].getType();
System.out.println("type: " + type);
System.out.println("genericType: " + genericType);
Type parameterType = genericType.getActualTypeArguments()[0];
System.out.println("parameter type: " + parameterType);
}
}
}
class Market{
List<Long> list = new ArrayList();
}
- getType()
这种方式获取到的类型会擦去泛型,返回List
输出type: interface java.util.List
- getGenericType()
这种方法会保留泛型信息
输出genericType: java.util.List<java.lang.Long>
通过调用genericType.getActualTypeArguments()
可以获取泛型具体的参数类型
输出parameter type: class java.lang.Long