/**
* @param source 被复制的对象:源对象
* @param target 要复制到的对象:目标对象
* @throw 见catch{}
* @Description 复制A对象有的属性值赋值给B, 常用与前端页面与后端交互传值,或者传输层见的属性值赋值
* @Date 2022/3/8 18:47
*/
public static void copyBeans(Object source, Object target) {
//只要有一个对象是空就结束了
if (source == null || target == null) {
return;
}
//通过对象.getClass获取源/目标对象的Class文件
Class sourceClass = source.getClass();
Class targetClass = target.getClass();
//获取源对象的所有成员对象
Field[] sourceClassFields =sourceClass.getDeclaredFields();
//目标对象的成员数组
Field[] targetClassFields=targetClass.getDeclaredFields();
//获取属性名称
try {
//遍历源对象的成员
for (Field field : sourceClassFields) {
//判断目标对象成员name是否在源对象中存在
if (!contiansName(targetClassFields,field.getName())) {
continue;
}
//通过源对象的成员field的name值获取目标对象中的成员targetField
Field targetField = targetClass.getDeclaredField(field.getName());
//判空
if (targetField != null) {
//如果源对象成员的成员类型和目标成员的类型一致,进行赋值
if (field.getType().equals(targetField.getType())) {
//解除成员属性的私有限制
field.setAccessible(true);
//获取source对应成员的属性的值
Object value = field.get(source);
//恢复成员属性的私有限制
field.setAccessible(false);
targetField.setAccessible(true);
//将value赋值给目标对象的成员
targetField.set(target, value);
//恢复成员属性的私有限制
targetField.setAccessible(false);
}
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* @Title contiansName
* @Description 判断fieldName是否有与Field数组中对象属性相同
* @param fields 数组
* @param fields 成员name
* @return true 存在 false 不存在
* @Date 2022/3/8 23:19
*/
protected static boolean contiansName(Field[] fields,String fieldName) {
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return true;
}
}
return false;
}
Java通过反射把A对象的属性值赋值给B实现拷贝(深拷贝)
最新推荐文章于 2023-09-20 08:47:16 发布