java反射双类型案例
2021-10-27 本文已影响0人
鄙人_阿K
随手记:A泛型的list集合,被B泛型实体射入
public static <T, E> List<T> addProcessInstanceIdModel(List<T> list, Class<E> clazz){
if (DailyUtil.isCollectionEmpty (list)){
for (int i = 0; i < list.size ( ); i++) {
try {
T t = list.get (i);
Field processInstanceIddField = clazz.getDeclaredField ("processInstanceIdd");
Field processInstanceIddField2 = t.getClass ().getDeclaredField ("processInstanceIdd");
Field idField = t.getClass ( ).getDeclaredField ("id");
if (idField.getGenericType ()==String.class){
idField.setAccessible (true);
// 拿到 t 对象中的属性值
String id = (String) idField.get (t);
Object o = userService.get (clazz, id);
if (DailyUtil.isObject (o)){
if (processInstanceIddField.getGenericType ()==String.class){
processInstanceIddField.setAccessible (true);
String idd = (String) processInstanceIddField.get (o);
// 反射进去
processInstanceIddField2.setAccessible (true);
processInstanceIddField2.set (t,idd);
}
}
}
list.set (i,t);
} catch (Exception e) {
e.printStackTrace ( );
}
}
}
return list;
}
使用:如果list内的实体不同,则调用多次即可
list = DailyUtil.addProcessInstanceIdModel (list,TblTasksPerMain.class);
list = DailyUtil.addProcessInstanceIdModel (list,SwjWork.class);