复制两个对象之间的属性
在使用jpa时,更新对象属性之前,需要先查出来entity对象,然后把前台传入到后端的form对象中不为空的属性,覆盖到entity对象中,在调用repository的save方法,完成更新。
这里在对属性覆盖式时,参考BeanUtils.copyProperties(),写了一段工具代码,里面可以自定义一些处理,后续可以优化
/**
* 把source 不为空的属性覆盖到 target
* @param source
* @param target
*/
private void transferFields(Object source, Object target) {
try {
Class sourceClass = source.getClass();
Class targetClass = target.getClass();
BeanInfo metricBeanInfo = Introspector.getBeanInfo(sourceClass);
BeanInfo targetBeanInfo = Introspector.getBeanInfo(targetClass);
// 获取sorce对象得属性值 然后复制给target对象
PropertyDescriptor[] propertyDescriptors = metricBeanInfo.getPropertyDescriptors();
PropertyDescriptor[] targetBeanInfoPropertyDescriptors = targetBeanInfo.getPropertyDescriptors();
Map<String, Method> methodMap = Arrays.stream(targetBeanInfoPropertyDescriptors)
.filter(t -> ObjectUtil.isNotNull(t.getWriteMethod()))
.collect(Collectors.toMap(t -> t.getReadMethod().getName(), t -> t.getWriteMethod()));
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
// 获取source对象的属性值
Method readMethod = propertyDescriptor.getReadMethod();
String fieldName = readMethod.getName();
Object value = readMethod.invoke(source);
Method writeMethod = methodMap.get(fieldName);
if (ObjectUtil.isEmpty(value) || Objects.isNull(writeMethod)) {
continue;
}
//复制给target对象
Class<?> parameterType = writeMethod.getParameterTypes()[0];
if (String.class.equals(parameterType)) {
value = String.valueOf(value);
} else if (Long.class.equals(parameterType)) {
value = Long.valueOf((String) value);
}
writeMethod.setAccessible(true);
writeMethod.invoke(target, value);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
获取一个class的属性以及父类的属性:
for循环
ArrayList<Field[]> fieldList = CollectionUtil.newArrayList();
for (Class currClass = dtoClass; currClass != null && currClass != Object.class;currClass = currClass.getSuperclass()) {
Field[] declaredFields = currClass.getDeclaredFields();
fieldList.add(declaredFields);
}