BeanUtils下的各个方法的作用

要对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!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值