實體對象之間相互傳值,如:VO對象的值賦給Entity對象,是代碼中常用功能,如果通過get、set相互賦值,則很麻煩,借助工具類BeanUtils可以輕松地完成操作。
BeanUtils依賴包導(dǎo)入
BeanUtils 是 Apache commons組件的成員之一,主要用于簡化JavaBean封裝數(shù)據(jù)的操作。使用BeanUtils必須導(dǎo)入相應(yīng)的jar包,BeanUtils的maven坐標(biāo)為
1
2
3
4
5
|
< dependency > < groupId >commons-beanutils</ groupId > < artifactId >commons-beanutils</ artifactId > < version >1.9.4</ version > </ dependency > |
示例
將前端傳來的學(xué)生排名信息(StudentVo對象)分別賦給學(xué)生對象(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對象的值 學(xué)號:" +getSno()+ " 名次:" +getRanking().toString()+ " 學(xué)期:" +getSchoolTerm(); } } |
將VO對象的值賦給實體對象,通過BeanUtils.copyProperties(目標(biāo),源),將源實體對象的數(shù)據(jù)賦給目標(biāo)對象,只把屬性名相同的數(shù)據(jù)賦值,目標(biāo)中的屬性如果在源中不存在,給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( "第三學(xué)期" ); 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()); } } |
運行結(jié)果:
StudentVo 中不存在sage屬性,獲得studentEntity對象的sage的值為null
以上就是java開發(fā)BeanUtils類解決實體對象間賦值的詳細內(nèi)容,更多關(guān)于使用BeanUtils工具類解決實體對象間賦值的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/guoyp2126/article/details/116381031