java 反射获取字段为List类型中的泛型类型
2024-08-20 23:23:52
在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);
}
}
}
最新文章
- CentOS 7.0安装配置Vsftp服务器
- solution to E: failed to fetch .......
- java考核完的心得
- caching redirect views leads to memory leak (Spring 3.1)
- 一款效果精致的 jQuery 多层滑出菜单插件
- 类似material design的电影应用源码
- mysql开启binlog
- sql 提取数字、字母、汉字
- 51nod1175 区间中第K大的数
- oracle添加表字段跟修改表字段属性
- BestCoder Round #36 (hdu5199)Gunner(水题)
- const 修饰成员函数体
- Unity User Group 北京站图文报道:《Unity虚拟现实实战技巧》
- 《跟我学Shiro》学习笔记 第一章:Shiro简介
- 用递归方法求n的阶乘
- Class.forname和ClassLoader.loadClass的源码分析
- JDK11&;12 新特性学习
- time模块的学习
- Xamarin.Android SharedPreferences的使用方法
- 201904Online Human Action Recognition Based on Incremental Learning of Weighted Covariance Descriptors