如何获取javaBean的get set 方法
已知属性名x --》 X ---》 getX ---》Method getX() (较为繁琐)
现通过PropertyDescriptor来实现
import java.util.*;
import java.beans.*;
import java.lang.reflect.*;
class Test
{
private int x;
private int y;
public Test(int x,int y)
{
this.x=x;
this.y=y;
}
public static void main(String[] args)throws Exception
{
Test t = new Test(2,3);
String propertyName = "x";
PropertyDescriptor pd = new PropertyDescriptor(propertyName,t.getClass());
Method getX = pd.getReadMethod();
System.out.println(getX.invoke(t));
Method setX = pd.getWriteMethod();
setX.invoke(t,30);
System.out.println(getX.invoke(t));
}
public void setX(int x)
{
this.x = x;
}
public int getX()
{
return x;
}
public void setY(int y)
{
this.y = y;
}
public int getY()
{
return y;
}
}
用Introspector类来实现获取java bean的信息
<span style="white-space:pre"> </span>BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : pds)
{
if(pd.getName().equals("x"))
{
System.out.println(pd.getReadMethod().invoke(t));
}
}
用MethodDescriptor类来实现获取java bean的信息MethodDescriptor[] mds = beanInfo.getMethodDescriptors();
for(MethodDescriptor md : mds)
{
Method m = md.getMethod();
if(m.getName().equals("getX"))
{
System.out.println(m.invoke(t));
}
}