好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java开发BeanUtils类解决实体对象间赋值

实体对象之间相互传值,如:VO对象的值赋给Entity对象,是代码中常用功能,如果通过get、set相互赋值,则很麻烦,借助工具类BeanUtils可以轻松地完成操作。

BeanUtils依赖包导入

BeanUtils 是 Apache commons组件的成员之一,主要用于简化JavaBean封装数据的操作。使用BeanUtils必须导入相应的jar包,BeanUtils的maven坐标为

?

1

2

3

4

5

< dependency >

     < groupId >commons-beanutils</ groupId >

     < artifactId >commons-beanutils</ artifactId >

     < version >1.9.4</ version >

</ dependency >

示例

将前端传来的学生排名信息(StudentVo对象)分别赋给学生对象(StudentEntity)和排名对象(RankingEntity),这三个类代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

@Data

public class StudentVo {

     private String sno;

     private String sname;

     private Integer ranking;

     private String schoolTerm;

 

     public String toString(){

         return "studentVo对象的值  sno:" +getSno()+ " sname:" +getSname()+ " ranking:" +getRanking().toString()+ " schoolTerm:" +getSchoolTerm();

     }

}

@Data

public class StudentEntity {

     private String sno;

     private String sname;

     private Integer sage;

 

     public String toString(){

         return "studentEntity对象的值 sno:" +getSno()+ " sname:" +getSname()+ " sage:" +getSage();

     }

}

@Data

public class RankingEntity {

     private String sno;

     private Integer ranking;

     private String schoolTerm;

 

     public String toString(){

         return "rankingEntity对象的值 学号:" +getSno()+ " 名次:" +getRanking().toString()+ " 学期:" +getSchoolTerm();

     }

}

将VO对象的值赋给实体对象,通过BeanUtils.copyProperties(目标,源),将源实体对象的数据赋给目标对象,只把属性名相同的数据赋值,目标中的属性如果在源中不存在,给null值,测试代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

public class App

{

     public static void main( String[] args ) throws InvocationTargetException, IllegalAccessException {

         StudentVo studentVo = new StudentVo();

         studentVo.setSno( "1" );

         studentVo.setRanking( 20 );

         studentVo.setSname( "胡成" );

         studentVo.setSchoolTerm( "第三学期" );

 

         System.out.println(studentVo.toString());

         StudentEntity studentEntity = new StudentEntity();

 

         BeanUtils.copyProperties(studentEntity,studentVo);

         System.out.println(studentEntity.toString());

 

         RankingEntity rankingEntity = new RankingEntity();

         BeanUtils.copyProperties(rankingEntity,studentVo);

         System.out.println(rankingEntity.toString());

     }

}

运行结果:

StudentVo 中不存在sage属性,获得studentEntity对象的sage的值为null

以上就是java开发BeanUtils类解决实体对象间赋值的详细内容,更多关于使用BeanUtils工具类解决实体对象间赋值的资料请关注其它相关文章!

原文链接:https://blog.csdn.net/guoyp2126/article/details/116381031

查看更多关于java开发BeanUtils类解决实体对象间赋值的详细内容...

  阅读:15次