要对Bean进行操作之前要进行属性的设置:Students中包括name和birthday
一、Object=加载类的对象
Name=类属性的名称
Value=所赋的值;
BeanUtils的getProperty(object,name)方法的返回值是String类型,所以可以直接输出;
//1.加载类
Class clss = Class.forName("需要加载类的路径,例如com.zds.Student");
//2.创建Bean对象
Student st = (Student) clss.newInstance();
//3.通过BeanUtils给对象属性赋值
BeanUtils.setProperty(st, "name", "zds")
//4.输出对象属性值
String str = BeanUtils.getProperty(st, "name");
System.out.println(str);
二、 使用BeanUtils自带的时间转化器转化时间
//创建Student Bean对象
Student st = new Student();
//使用自带转化器转化时间格式
ConvertUtils.register(new DateLocaleConverter(), Date.class);
//赋值给birth属性
BeanUtils.setProperty(st, "birth", "1993-11-15");
//输出birth属性的值
System.out.println(st.getBirth());
三、自定义日期格式转换器
首先定义一个日期格式转换器
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
//当value参数等于空时返回空
if(value==null){
return null;
}
//自定义时间的格式为SimpleDateFormat
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", "1993-11-15");
//输出
System.out.println(st.getBirth());
ConvertUtils.register(new Converter()中,new Converter()就相当于重写了Converter类中方法:
that is all.thank you!!