package cn.itcast.day1;
public class ReflectPoint
{
private int x;
public int y;
public ReflectPoint()
{
}
public ReflectPoint(int x, int y)
{
super();
this.x = x;
this.y = y;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
public class IntroSpector
{
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
ReflectPoint rp=new ReflectPoint(3, 9);
String propertyName="x";
Object setVal=7;
BeanInfo beanInfo = Introspector.getBeanInfo(rp.getClass());
PropertyDescriptor[] pds= beanInfo.getPropertyDescriptors();
for( PropertyDescriptor pd :pds )
{
if(pd.getName().equals( propertyName))
//这里如果用 pd.getName()==propertyName的话判断结果是false。但是这两个变量都是String的且值也是相同.加上toString 也一样。
{
Method setMethod=pd.getWriteMethod();
setMethod.invoke(rp, setVal);
break;
}
}
System.out.println(rp.getX());
}
}
|