日常小结-内省、beanutils

内省(Introspector)

用来操作bean属性的。

内省访问javaBean属性的两种方式:
1. 通过PropertyDescription类操作Bean的属性。
2. Introspctor类获得Bean对象的BeanInfo,然后通过BeanInfo来获取属性的描述器(PropertyDescriptior)。通过这个属性描述器就可以获得某个属性的getter/setter方法。然后通过反射机制来调用这些方法。

example:

public class Demo1{
    @Test
    public void test1() throws Exception{
    BeanInfo info = Introspector.getBeanInfo(Persion.class,Object.class);
    PropertyDescriptor[] pds = info.getPropertyDescriptors();
    for(PropertyDescriptor pd:pds){
        System.out.println(pd.getName());
        }
    }
}
public void test2() throws Exception{
    Person p = new Person();
    PropertyDescriptor pd = new PropertyDescriptor("age",Person.class);
    Method method = pd.getWriteMethod();
    method.invoke(obj,45)
    System.out.println(p.getAge());

    method = pd.getReadMethod();
    System.out.println(method.invoke(p,null));
}
public void test2() throws Exception{
    Person p = new Person();
    PropertyDescriptor pd = new PropertyDescriptor("age",Person.class);
    System.out.println(pg.getPropertyType());//获得属性的类型。
}

BeanUtils

apache的bean
新建lib文件夹,添加jar包。
commons-beantuils
commons-logging
右键build path;

public void test1()throws IllegalAccessEception, InvocationT{
    Person p = new Person();
    BeanTtils.setProperty(p,"name","xcc");
    System.out.println(p.getName());
}

可以自动类型转换。但只支持8中基本数据类型。

对其其他的类型。需要注册一个转换类。例如对于Date类型。
ConverUtils.register(new Converter(){
pubic Object convert(Class type, Object value){
if(value==null){
return null;
}
if(value instanceof String){
System.out.println(“不转”);
throw new ConversionException(“只支持string类型的”);
}
String str = (String) value;
if(str.trim().equals(“”)){
return null;
}
SimpleDateFormat df = new SimpleDateFormat(“YYYY-MM-dd”);
try{
return df.parse(str);
}catch( ParseException e){
throw new RuntimeException(e); //异常链不能断
}
}
},Date.class);

BeanUtils.populate()一次完成。多项任务。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值