操作Bean的几种方式(内省Introspector,BeanUtils,Map)

1.传统方式
Person p=new Person();
PropertyDescriptor pds=new PropertyDescriptor("age",Person.class);
//得到写方法
Method method=pds.getWriteMethod();//相当于获取set方法
method.invoke(p, 25);//给对象赋值
//System.out.println(p.getAge());
//获取对象读方法
method=pds.getReadMethod();
System.out.println(method.invoke(p,null));

2.通过sun公司的内省Introspector
    BeanInfo info=Introspector.getBeanInfo(Person,class,Object.class);    //得到bean自己属性
    PropertyDescriptor[    ] pds=info.getPropertyDescriptors();
    for(PropertyDescriptor pd:pds){
    System.out.print(pd.getName());
}

   3    .第三方Apache公司的 BeanUtils方式
            
Person p=new Person();
        BeanUtils.setProperty(p, "name", "hhb");//参数:对象,属性,值
        System.out.println(p.getName());

4.    通过Map
     Map map=new HashMap();
map.put("name","hhb");
map.put("age","25");
map.put("birthday","1987-8-2");
ConvertUtils.register(new DateLocaleConverter(), Date.class);
Person bean=new Person();
BeanUtils.populate(bean, map);// 注意map中属性名称必须与bean(Person)中的属性名字一致

5.    BeanUtils只支持8种基本数据类型,对于其它类型则要注册转换器,以下以Data为实例
        第一种,自己写:
                ConvertUtils.register(new Converter(){
public  <T> T convert(Class <T> type, Object value) { //泛型定义有待学习
// TODO Auto-generated method stub
//System.out.println(value);
if(value==null){
return null;
}
if(!(value instanceof String)){
throw new ConversionException("只支持String类型转换!");
}
String str=(String) value;
if(str.trim().equals("")){
return null;
}
SimpleDateFormat df=new  SimpleDateFormat("yyyy-MM-dd");
try{
return   (T)  df.parse(str);
}catch(Exception e){
throw new RuntimeException(e);
}
}
},  Date.class);  
第二种,使用Apache 公司的Converer的实现类,其它实现可以参阅API文档,
        ConvertUtils.register(new  DateLocaleConverter() , Date.class);//但此实现类,有个BUG,不能传空,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值