内省(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()一次完成。多项任务。