---------------------- android培训、java培训、期待与您交流! ----------------------
内省(IntroSpector)
主要是对JavaBean进行操作,JavaBean是特殊的Java类,包含get()、set()方法,JavaBean的属性是根据方法名称而来。
例:
目的:用反射来操作JavaBean,得到对应的get、set方法
public class ReflectPoint{
private int x;
private int y;
public int getX(){
return x;
}
public int setX(int x){
this.x=x;
}
public int getY(){
return y;
}
public int setY(int y){
this.y=y;
}
public ReflectPoint(int x,int y){
super();
this.x=x;
this.y=y;
}
}
public class IntroSpectorTest{
public static void main(String[] args) throws Exception{
ReflectPoint pt1= new ReflectPoint(3,5);
String propertyName = "x";//指定属性名
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass);
//属性描述符,1、属性名 2、指定某个类作为JavaBean,从JavaBean里获取属性
Method methodGetX=pd.getReadMethod()//得到只读的方法
Object retVal = methodGetX.invoke(pt1);//调用pt1对象的Get方法
System.out.println(retVal);//值为:3
Method methodSetX=pd.getWriteMethod()//得到写入的方法
methodSetX.invoke(pt1,7);//调用pt1对象的Set方法
System.out.println(pt1.getX());
}
//还可以把上面的get、set重构成方法:选中准备重构的代码-->右键-->重构(Refactor)-->Extract Mathod(抽取方法)
例:
public class IntroSpectorTest{
public static void main(String[] args) throws Exception{
ReflectPoint pt1= new ReflectPoint(3,5);
String propertyName = "x";//指定属性名
Object retVal = getProperty(pt1,propertyName);//得到这个对象的属性名
System.out.println(retVal);
Object value = 7;
setProperty(pt1,propertyName,value);//传入这个对象的属性名的值
System.out.println(pt1.getX());
}
private static Object getProperty(Object pt1,String propertyName) throws IntrospectionException,
IllegalAccessException,InvocationTargetException{
/*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass);
//属性描述符,1、属性名 2、指定某个类作为JavaBean,从JavaBean里获取属性
Method methodGetX=pd.getReadMethod()//得到只读的方法
Object retVal = methodGetX.invoke(pt1);*/
//用复杂的方式来写
BeanInfo beanInfo= IntroSpector.getBeanInfo(pt1.getClass());
//把pt1这个java类当成一个JavaBean来看,BeanInfo代表这个JavaBean的信息
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//只能得到所有属性的描述,不能得到指定属性描述
Object retVal = null;
for(PropertyDescriptor pd : pds){ //对属性进行迭代
if(pd.getName().equals(propertyName)){
Method methodGetX=pd.getReadMethod()//得到只读的方法
retVal = methodGetX.invoke(pt1);
break;
}
}
return retVal;
}
private static void setProperty(Object pt1,String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException,InvocationTargetException{
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass);
//属性描述符,1、属性名 2、指定某个类作为JavaBean,从JavaBean里获取属性
Method methodSetX=pd.getWriteMethod();//得到只读的方法
methodSetX.invoke(pt1,value);
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------