/**
* 创建一个新的类 并赋给属性名相同类型相同的属性值
* @param o1 目标对象
* @param o2Class 赋值对象
* @throws IllegalAccessException
*/
public static <T> T createObject(Object o1, Class<T> o2Class) throws IllegalAccessException, InstantiationException {
T o2 = o2Class.newInstance();
Class<?> o1Class = o1.getClass();
//o1属性
Field[] o1Fields = o1Class.getDeclaredFields();
//o2属性
Field[] o2Fields = o2Class.getDeclaredFields();
//如果没有属性则不处理
if (o1Fields.length == 0 ||o2Fields.length == 0){
return o2;
}
//根据名称转小写然后分组
Map<String, List<Field>> nameMap = Arrays.stream(o1Fields).collect(Collectors.groupingBy(s -> s.getName().toLowerCase()));
for (Field o2Field : o2Fields) {
List<Field> fields = nameMap.get(o2Field.getName().toLowerCase());
//不存在名称相同不处理
if (CollUtil.isEmpty(fields)){
continue;
}
//名称相同的属性o1
Field o1field = fields.get(0);
//类型不同
if (!o1field.getGenericType().toString().equalsIgnoreCase(o2Field.getGenericType().toString())){
String o1Types = o1field.getGenericType().toString();
String o2Types = o2Field.getGenericType().toString();
String o1Type = o1Types.substring(o1Types.lastIndexOf(".")+1);
String o2Type = o2Types.substring(o2Types.lastIndexOf(".")+1);
//特殊情况排除
if (!(o1Type.equals("int")&&o2Type.equals("Integer") ||
o1Type.equals("Integer")&&o2Type.equals("int")||
o1Type.equals("char")&&o2Type.equals("Character") ||
o1Type.equals("Character")&&o2Type.equals("char"))){
continue;
}
}
//打破私有访问限制
o2Field.setAccessible(true);
o1field.setAccessible(true);
//赋值
o2Field.set(o2,o1field.get(o1));
}
return o2;
}
Java暴力反射copy对象
最新推荐文章于 2023-05-26 13:15:44 发布