BeanUtils工具包是由Apache公司所开发,主要是方便程序员对Bean类能够进行简便的操作。
在使用BeanUtils工具包之前我们需要的Jar包有以下几种:
(1) BeanUtils相关包
commons-beanutils-1.8.3.jar
commons-beanutils-1.8.3-javadoc.jar
commons-beanutils-1.8.3-javadoc.jar
commons-beanutils-bean-collections-1.8.3.jar
commons-beanutils-core-1.8.3.jar
(2) Logic4j相关包
commons-logging.jar
log4j.jar
既然要对Bean对象进行操作,那么我们先创建一个Bean的测试类:
public class Student {
private String name;
private int age;
private Date birth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
一、先赋值Bean对象里的字段属性,然后再取值:
@Test
public void test01() throws Exception{
//1.加载类
Class clss = Class.forName("com.L.introspector.Student");
//2.创建Bean对象
Student st = (Student) clss.newInstance();
//3.通过BeanUtils给对象属性赋值
BeanUtils.setProperty(st, "name", "L。");
//4.输出对象属性值
String str = BeanUtils.getProperty(st, "name");
System.out.println(str);
}
BeanUtils的setProperty(object,name,value)方法需要的参数分别是
Object=加载类的对象
Name=类属性的名称
Value=所赋的值;
BeanUtils的getProperty(object,name)方法的返回值是String类型,所以可以直接输出;
二、 使用BeanUtils自带的时间转化器转化时间
@Test
public void test03() throws Exception{
//创建Student Bean对象
Student st = new Student();
//使用自带转化器转化时间格式
ConvertUtils.register(new DateLocaleConverter(), Date.class);
//赋值给birth属性
BeanUtils.setProperty(st, "birth", "1991-09-25");
//输出birth属性的值
System.out.println(st.getBirth());
}
三、 自定义日期格式转换器
@Test
public void test04()throws Exception{
//创建Student对象
Student st = new Student();
//使用CovertUtils注册创建一个日期格式转换器
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
//当value参数等于空时返回空
if(value==null){
return null;
}
//自定义时间的格式为yyyy-MM-dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
//创建日期类对象
Date dt = null;
try {
//使用自定义日期的格式转化value参数为yyyy-MM-dd格式
dt = sdf.parse((String)value);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//返回dt日期对象
return dt;
}
}, Date.class);
//给birth赋值
BeanUtils.setProperty(st, "birth", "1991-09-25");
//输出
System.out.println(st.getBirth());
}
ConvertUtils.register(new Converter()中,new Converter()就相当于重写了Converter类中方法:
Public class MyConerter implements Converter{
//并且在此处创建了匿名的对象
}