对象之间相同属性快速复制的三种方法

1:使用commons-beanutils包中的BeanUtils类

用法:引入依赖

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.7.0</version>
</dependency>
import org.apache.commons.beanutils.BeanUtils;

/*BeanUtils.copyProperties(target,source);
与上边正好相反,将source的属性复制到target(属性字段相同才会进行复制,否则不复制)*/
BeanUtils.copyProperties(studentVo, student);

注意:此种方法需要抛出异常

2:使用spring-beans5.0.8包中的BeanUtils类

用法:引入依赖

<dependency>
 	<groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.2.4.RELEASE</version>
</dependency>
import org.springframework.beans.BeanUtils;

//BeanUtils.copyProperties(source, target);
//将source的属性复制到target(属性字段相同才会进行复制,否则不复制)
BeanUtils.copyProperties(student, studentVo);

3:cglib提供的copy方式

用法:引入依赖

<dependency>
   <groupId>cglib</groupId>
   <artifactId>cglib</artifactId>
   <version>3.1</version>
</dependency>
import net.sf.cglib.beans.BeanCopier;

//将student的属性复制到studentVo(属性字段相同才会进行复制,否则不复制)
BeanCopier copier = BeanCopier.create(Student.class,StudentVo.class,false);
copier.copy(student,studentVo,null);

备注:三者的性能依次为 3 好于 2,2 好于 1

还有多种复制方式,暂不作列举

发布了27 篇原创文章 · 获赞 1 · 访问量 836

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/105235179
今日推荐