java開發(fā)BeanUtils類解決實體對象間賦值
實體對象之間相互傳值,如:VO對象的值賦給Entity對象,是代碼中常用功能,如果通過get、set相互賦值,則很麻煩,借助工具類BeanUtils可以輕松地完成操作。
BeanUtils依賴包導(dǎo)入
BeanUtils 是 Apache commons組件的成員之一,主要用于簡化JavaBean封裝數(shù)據(jù)的操作。使用BeanUtils必須導(dǎo)入相應(yīng)的jar包,BeanUtils的maven坐標(biāo)為
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
示例
將前端傳來的學(xué)生排名信息(StudentVo對象)分別賦給學(xué)生對象(StudentEntity)和排名對象(RankingEntity),這三個類代碼如下:
@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值,測試代碼如下:
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類解決實體對象間賦值的詳細(xì)內(nèi)容,更多關(guān)于使用BeanUtils工具類解決實體對象間賦值的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot項目實現(xiàn)短信發(fā)送接口開發(fā)的實踐
本文主要介紹了SpringBoot項目實現(xiàn)短信發(fā)送接口開發(fā)的實踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10
Spring Boot中的WebSocketMessageBrokerConfigurer接口使用
在SpringBoot中,我們可以使用 WebSocketMessageBrokerConfigurer接口來配置WebSocket消息代理,以實現(xiàn)實時通信,具有一定的參考價值,感興趣的可以了解一下2023-11-11

