/**
* 该类主要用于反射赋值,
* t1 取值类
* t2 赋值类
* reflection t1与t2的对应关系 如: String str = "xref1:scNo,xref2:scName,xref3:dutyEmp"; 即将 t1 中 scNo 赋值给 t2 中 xref1
* 对应关系必须是两个对象中的字段, 区分 大小写
*/
@Service("ReflectionServiceImpl")
public class ReflectionServiceImpl implements IReflectionService {
private static Logger log= LoggerFactory.getLogger(ClaimLineReflectionServiceImpl.class);
@Override
public <T> T test1(T t1, T t2, String reflection) {
try{
Class t1Class = t1.getClass();
Class t2Class = t2.getClass();
List<Field> allFields = new ArrayList<>();
allFields.addAll(Arrays.asList(t1Class.getDeclaredFields()));
Class clazzSuper = t1Class.getSuperclass();
while (clazzSuper != Object.class) {
allFields.addAll(Arrays.asList(clazzSuper.getDeclaredFields()));
clazzSuper = clazzSuper.getSuperclass();
}
HashMap<String, Object> hashMap = new HashMap<>();
allFields.stream().forEach(field->{
try {
field.setAccessible(true);
String fieldName = field.getName();
Object obj = field.get(t1);
hashMap.put(fieldName,obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
for (String str1:reflection.split(",")){
if (StringUtils.isNotEmpty(str1)){
String[] str2 = str1.split(":");
Field field = t2Class.getDeclaredField(str2[0]);
field.setAccessible(true);
field.set(t2,hashMap.get(str2[1]));
}
}
}catch (Exception e){
log.error("反射赋值出现异常:" + e);
e.printStackTrace();
}
return t1;
}
}
泛型与 反射 给字段赋值
最新推荐文章于 2022-06-12 21:57:45 发布