项目中需要使用对象(DO)属性赋值给包含其属性子集的对象(DTO)或者显示层对象(VO)。
这种场景下需要大量调用get set方法,当属性较多时代码量较大而且非常繁琐。
因此采用反射机制,对此类场景进行简单封装。
import java.lang.reflect.Field;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 对象source私有属性复制给destination对象的同名私有属性工具
* 注意:只支持属性名完全相同的属性复制,支持忽略一些属性,其他需要手动get set
* @author 明明如月 w1251314@sohu.com
*/
public class PropertyUtils {
/**
* 将source对象的属性填充到destination对象对应属性中
* @param source 原始对象
* @param destination 目标对象
*/
public static <S,D> void copyProperties(S source, D destination) {
Class clsDestination;
try {
clsDestination = Class.forName(destination.getClass().getName());
Class clsSource = Class.forName(source.getClass().getName());
Field[] declaredFields = clsDestination.getDeclaredFields();
for (Field field : declaredFields){
field.setAccessible(true);
String fieldName = field.getName();
try{
//跳过serialVersionUID
if("serialVersionUID".equals(fieldName)){
continue;
}
Field sourceField = clsSource.getDeclaredField(fieldName);
sourceField.setAccessible(true);
field.set(destination,sourceField.get(source));
}catch (NoSuchFieldException e){
// continue;
}
}
} catch (Exception e) {
throw new RuntimeException("PropertyUtils 属性转换错误");
}
}
/**
* 将source对象的属性填充到destination对象对应属性中
* @param source 原始对象
* @param destination 目标对象
* @param ignoreProperties 不转换的属性
*/
public static <S,D> void copyProperties(S source, D destination,String... ignoreProperties) {
Class clsDestination ;
try {
clsDestination = Class.forName(destination.getClass().getName());
Class clsSource = Class.forName(source.getClass().getName());
Field[] declaredFields = clsDestination.getDeclaredFields();
for (Field field : declaredFields){
String fieldName = field.getName();
Set<String> collect = Stream.of(ignoreProperties).collect(Collectors.toSet());
//跳过serialVersionUID
collect.add("serialVersionUID");
if(collect.contains(fieldName)){
continue;
}
try{
field.setAccessible(true);
Field sourceField = clsSource.getDeclaredField(fieldName);
sourceField.setAccessible(true);
field.set(destination,sourceField.get(source));
}catch (NoSuchFieldException e){
// 没有对应属性跳过;
}
}
} catch (Exception e) {
throw new RuntimeException("PropertyUtils 属性转换错误");
}
}
}
对于那些不重复的属性赋值,直接调用少量set方法即可。
不过最近发现Spring的提供了对应方法
在org.springframework.beans.BeanUtils类中有静态方法可以实现同名属性拷贝。
/**
* Copy the property values of the given source bean into the target bean.
* <p>Note: The source and target classes do not have to match or even be derived
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
public static void copyProperties(Object source, Object target) throws BeansException {
copyProperties(source, target, null, (String[]) null);
}
Note部分提到source和target类不必所有属性都匹配,而且不需要有继承关系。
另外值得注意的是
/**
* Copy the property values of the given source bean into the given target bean,
* ignoring the given "ignoreProperties".
* <p>Note: The source and target classes do not have to match or even be derived
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}
重载的此方法可以添加String类型的属性,这些属性在copy时将被忽略,非常实用。
受该方法启发,我们自己写的同名属性复制类也可以添加如此方法。
不过强烈不建议用属性拷贝工具类,建议定义转换工具类,然后写转换方法。
转换容易造成遗漏,类型错误等等。
另外可以参见https://blog.csdn.net/w605283073/article/details/89163627 使用GenerateO2O插件可以节省很大工作量。
如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。
另外欢迎加入我的知识星球,知识星球ID:15165241 一起交流学习。
https://t.zsxq.com/Z3bAiea 申请时标注来自CSDN。