------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
(1)JavaBean是一种特殊的Java类,主要用于传递数据信息,这种java类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。
Javabean的属性是根据其中的setter和getter方法来确定的。
去掉set或get前缀剩余部分就是属性名,如果剩余部分的第二个字母是小写的,则把剩余部分的首字母改成小写的,如果第二个字母是大写的,则首字母保持原样
例如 gettime—time,setTime—time,getCPU—CPU
总之,一个类被当做javabean使用时,javabean的属性是根据方法名来判断的,它根本看不到java类内部的成员变量。
(2)一个符合javabean特点的类可以被当做普通类一样使用,
(3)内省的英文单词,IntroSpector,它主要对javabean进行操作
(4)使用内省简单操作javabean
public static void main(String[] args)throws Exception {
// 实例一个javabean对象
ReflectPoint pt1=new ReflectPoint(3, 5);
//设置要操作的属性
String propertyName="x";
//重构抽取getProperty方法
Object retValue = getProperty(pt1, propertyName);
//打印属性值
System.out.println(retValue);
//将x属性设置为7
Object value=7;
//重构抽取setProperty方法
setProperty(pt1, propertyName, value);
//打印设置后的属性值
System.out.println(pt1.getX());
}
private static void setProperty(Object pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
//创建一个属性描述器
PropertyDescriptor pd=new PropertyDescriptor(propertyName,pt1.getClass());
//通过属性描述器获得属性的写方法
Method methodSetX=pd.getWriteMethod();
//执行写方法
methodSetX.invoke(pt1,value);
}
private static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
//创建一个属性描述器
PropertyDescriptor pd=new PropertyDescriptor(propertyName,pt1.getClass());
//通过属性描述器获得属性的读方法
Method methodGetX=pd.getReadMethod();
//执行读方法,获得返回值
Object retValue=methodGetX.invoke(pt1);
return retValue;
}
(5)内省综合案例
采用遍历BeanInfo的所有属性方式来查找和设置某个ReflectPoint对象的x属性。在程序中把一个类当作JavaBean来看,就是调用IntroSpector.getBeanInfo方法,得到的BeanInfo对象封装了把这个类当作JavaBean看的结果信息
private static ObjectgetProperty(Object pt1, String propertyName)
throws Exception
BeanInfo beaninfo=Introspector.getBeanInfo(pt1.getClass());
//通过beaninfo获得多个属性描述器
PropertyDescriptor[] pds=beaninfo.getPropertyDescriptors();
//遍历属性,匹配要找的属性
Object retValue=null;
for (PropertyDescriptor pd : pds) {
if(pd.getName().equals(propertyName)){
MethodmethodGetX=pd.getReadMethod();
retValue=methodGetX.invoke(pt1);
break;
}
}
return retValue;
}
(6)使用BeanUtils操作javabean
BeanUtils.getProperty(pt1, "x");
BeanUtils.setProperty(pt1, "x", 9);//能够实现字符串与int类型的自动转换