在java编程时,经常会使用反射去处理对象,有时会需要知道List的泛型类型:示例操作如下
obj = pojo.newInstance();// 首先得到pojo所定义的字段Field[] fields = pojo.getDeclaredFields();for (Field curField : fields) {// 设置字段可访问(必须,否则报错)curField.setAccessible(true);Class<?> curFieldType = curField.getType();// 集合List元素if (curFieldType.equals(List.class)) {// 当前集合的泛型类型Type genericType = curField.getGenericType();if (null == genericType) {continue;}if (genericType instanceof ParameterizedType) {ParameterizedType pt = (ParameterizedType) genericType;// 得到泛型里的class类型对象Class<?> actualTypeArgument = (Class<?>)pt.getActualTypeArguments()[0];List<Object> curEleList = new ArrayList<>();Object actualType = actualTypeArgument.newInstance();//....actualType字段处理curEleList.add(actualType); curField.set(obj, curEleList);}}}