演示用eclipse 自动生成ReflectPoint 类的setter 和getter 方法。
直接new 一个PropertyDescriptor 对象的方式来让大家了解JavaBean API 的价值,先用
一段代码读取JavaBean 的属性,然后再用一段代码设置JavaBean 的属性。
演示用eclipse 将读取属性和设置属性的流水帐代码分别抽取成方法:
只要调用这个方法,并给这个方法传递了一个对象、属性名和设置值,它就能完成属性
修改的功能。
得到BeanInfo 最好采用“obj.getClass()”方式,而不要采用“类名.class”方式,这样程
序更通用。
采用遍历BeanInfo 的所有属性方式来查找和设置某个RefectPoint 对象的x 属性。在程
序中把一个类当作JavaBean 来看,就是调用IntroSpector.getBeanInfo 方法,得到的BeanInfo
对象封装了把这个类当作JavaBean 看的结果信息。
演示用eclipse如何加入jar包,先只是引入beanutils包,等程序运行出错后再引入logging
包。
在前面内省例子的基础上,用BeanUtils 类先get 原来设置好的属性,再将其set 为一个
新值。
get 属性时返回的结果为字符串,set 属性时可以接受任意类型的对象,通常使用字符串。
用PropertyUtils 类先get 原来设置好的属性,再将其set 为一个新值。
get 属性时返回的结果为该属性本来的类型,set属性时只接受该属性本来的类型。
演示去掉JavaBean(ReflectPoint)的 public 修饰符时,BeanUtils工具包访问 javabean
属性时出现的问题。
Eg:package javaBean.cn.itcast;
import java.beans.BeanInfo;
importjava.beans.IntrospectionException;
import java.beans.Introspector;
importjava.beans.PropertyDescriptor;
importjava.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
importorg.apache.commons.beanutils.BeanUtils;
public class BeansTest {
public static void main(String[]args) throws Exception {
// TODO Auto-generated methodstub
Person p = new Person();
p.setName("刘昭");
String propertiesName ="name";
String name = extracted(p,propertiesName);//演示了用eclipse
抽取方法
System.out.println(name);
String propertiesAge ="age";
int age = 23;
SetAge(p, propertiesAge, age);
String name1 = BeanUtils.getProperty(p,"name");// 使用
beanUtils工具包进行获取和设置属性(尽管这些属性是私有的,可是有方法啊,是不是
很方便, javabean中的属性的首字母必须是小写的)
System.out.println(BeanUtils.getProperty(p,
"name").getClass().getName());
System.out.println(name1);
BeanUtils.setProperty(p,"age", 19);
System.out.println(p.getAge());
/*打印结果
* 刘昭
23
java.lang.String
刘昭
19*/
}
private static void SetAge(Personp, String propertiesAge, int age)
throws IntrospectionException,IllegalAccessException,
InvocationTargetException {
PropertyDescriptor bp1 = newPropertyDescriptor(propertiesAge,
p.getClass());
Method methodSetAge =bp1.getWriteMethod();
methodSetAge.invoke(p,age);
System.out.println(p.getAge());
}
private static Stringextracted(Object p, String propertiesName)
throws IntrospectionException,IllegalAccessException,
InvocationTargetException {
/*PropertyDescriptor bp = new
PropertyDescriptor(propertiesName,p.getClass());
Method methodGetName =bp.getReadMethod();
Object readVal =methodGetName.invoke(p);
System.out.println(readVal);*/
BeanInfo beanInfo =Introspector.getBeanInfo(p.getClass());
PropertyDescriptor[] pds =
beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertiesName))
{
Method methodGetX =pd.getReadMethod();
retVal =(String)methodGetX.invoke(p);
break;
}
}
return (String) retVal;
}
}