JavaBean是一种特殊的JAVA类,他的名称和方法符合一定的规则。javaBean主要用于数据操作。
如果要在两个模块之间传递多个信息,可以将这些信息封装在一个JavaBean中,这种JavaBean的实例对象通常称之为值对象。这些信息在类中用私有字段来存储,如果读取或设置这些字段的值,则需要通过一些相应的方法来访问。
一个符合JavaBean方法规则的Java类可以当做普通类,也可以当做JavaBean类。
第一种方法创建PropertyDescriptor对象,然后得到方法的对象,对其进行赋值和取值
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntrospectorTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt = new ReflectPoint(3,5);
String propertyName="x";
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt.getClass());
Method methodX=pd.getReadMethod();
methodX.invoke(pt);
}
}
第二种方法通过内省的getBeanInfo方法得到BeanInfo对象,然后得到属性数组,然后对其遍历,如果属性是需要的就获取它的值。
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntrospectorTest2 {
public static void main(String[] args) throws Exception {
ReflectPoint pt = new ReflectPoint(3,5);
String propertyName="x";
BeanInfo beanInfo=Introspector.getBeanInfo(pt.getClass());
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
Object retVal=null;
for(PropertyDescriptor pd:pds){
if(pd.getName().equals(propertyName)){
Method methodX=pd.getReadMethod();
retVal=methodX.invoke(pt);
}
}
}
}
对于JavaBean的操作也可以使用BeanUtils工具,只需要使用它的setProperty和getProperty方法进行赋值和取值操作即可。