一 BeanUtils
commons-beanutils
是Apache开源组织提供的用于操作JAVA BEAN的工具包。使用commons-beanutils
,我们可以很方便的对bean对象的属性进行操作。准备Student-Bean
public class Student {
/**
* 学生学号
*/
private String id;
/**
* 学生名字
*/
private String name;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private Integer age;
/**
* 课本号
*/
List<String> list;
}Teacher-Bean
public class Teacher {
/**
* 教师工号
*/
private String tId;
/**
* 老师名字
*/
private String name;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private Integer age;
/**
* 教龄
*/
private Integer year;
/**
* 课本号
*/
List<String> list;
}
1.copyProperties
对于所有属性名称相同的情况,将属性值从源bean复制到目标bean。
/**
* copyProperties ()
*/
public void copyProperties() throws Exception {
List<String> list=new ArrayList<>();
list.add("A1");
list.add("B1");
list.add("C1");
Student st=Student.builder()
.id("1")
.name("小明")
.sex("男")
.age(33)
.list(list)
.build();
System.out.println("学生:"+st);
Teacher t=new Teacher();
BeanUtils.copyProperties(t,st);
System.out.println("老师:"+t);
}
//学生:Student(id=1, name=小明, sex=男, age=33, list=[A1, B1, C1])
//老师:Teacher(tId=null, name=小明, sex=男, age=33, year=null, list=[A1, B1, C1])
2.copyProperty
将指定的属性值复制到指定的目标bean,执行所需的任何类型转换。
/**
* copyProperty()
*/
public void copyProperty() throws Exception{
Student st=Student.builder()
.build();
BeanUtils.copyProperty(st,"name","科比");
System.out.println(st);
}
//Student(id=null, name=科比, sex=null, age=null, list=null)
3.setProperty
给指定bean的指定属性的值赋值
/**
* setProperty()
* getProperty()
* 给对象属性赋值
*/
public void setProperty() throws Exception {
People p=People.builder()
.id("1")
.name("科比")
.sex("男")
.age(22).build();
BeanUtils.setProperty(p,"name","杜兰特");
BeanUtils.getProperty(p,"name");
System.out.println("人:"+p);
}
//人:People(id=1, name=杜兰特, sex=男, age=22)