JAVABean是一種特殊的java類,該類中的方法以set和get打頭。
javaBean的方法和屬性命名之間的關係,如果set和get後面的單詞的第二個字母是小寫的則屬性名稱的第一個字母必爲小寫
如gettime()則該JAVABean的屬性爲time.如果是getTime()屬性也是time。
而如果第二個字母是大寫的話,則JAVABean的屬性名稱的第一個字母爲大寫
如getUSB-------------->USB
總結
gettime()--------------->time
getTime()--------------->time
getUSB()---------------->USB
下面是通過PropertyDescriptor類來操作JAVABean的一個例子,其中的setProperty是通過myEclipse的重構來獲得的
package cn.yangtao.reflect;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.*;
import java.util.*;
public class ColectionReflect {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
ReflectPoint p=new ReflectPoint(5,2);
//獲取JAVABean的屬性值
String propertyName="x";
Object retVal = getProperty(p, propertyName);
System.out.println(retVal);
//設置JAVABean的值
int setVal=4;
PropertyDescriptor pd=new PropertyDescriptor(propertyName,p.getClass());
Method setX=pd.getWriteMethod();
setX.invoke(p, setVal);
System.out.println(getProperty(p, propertyName));
}
private static Object getProperty(ReflectPoint p, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd=new PropertyDescriptor(propertyName,p.getClass());
Method getX=pd.getReadMethod();
Object retVal=getX.invoke(p);
return retVal;
}
}
接下來通過Introspector類來獲取JAVABean的屬性,但是此方法的有個缺點就是不能一個一個屬性的取出來。此時就可以使用foreach來輸出
private static Object getProperty(ReflectPoint p, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
BeanInfo beanInfo=Introspector.getBeanInfo(p.getClass());
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
Object retVal=null;
for(PropertyDescriptor pd:pds){
if(pd.getName().equals(propertyName)){
Method getX=pd.getReadMethod();
retVal=getX.invoke(p);
break;
}
}
return retVal;
}