实体对象之间赋值——BeanUtils的使用
发布日期:2021-05-07 01:32:21 浏览次数:24 分类:原创文章

本文共 2089 字,大约阅读时间需要 6 分钟。

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

BeanUtils依赖包导入

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

<dependency>    <groupId>commons-beanutils</groupId>    <artifactId>commons-beanutils</artifactId>    <version>1.9.4</version></dependency>

示例

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

@Datapublic 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();    }}@Datapublic class StudentEntity {       private String sno;    private String sname;    private Integer sage;    public String toString(){           return "studentEntity对象的值 sno:"+getSno()+" sname:"+getSname()+" sage:"+getSage();    }}@Datapublic class RankingEntity {       private String sno;    private Integer ranking;    private String schoolTerm;    public String toString(){           return "rankingEntity对象的值 学号:"+getSno()+" 名次:"+getRanking().toString()+" 学期:"+getSchoolTerm();    }}

将VO对象的值赋给实体对象,通过BeanUtils.copyProperties(目标,源),将源实体对象的数据赋给目标对象,只把属性名相同的数据赋值,目标中的属性如果在源中不存在,给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("第三学期");        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

上一篇:hdu2552 三足鼎立
下一篇:约瑟夫环问题求解方法总结

发表评论

最新留言

很好
[***.229.124.182]2025年04月10日 15时12分52秒