IntroSpector-->JavaBean-->符合特殊规则的类
类中的属性对象都是可以用 set get方法来修改和获取值 注意
类型 get()_____________有返回值____不接受参数
void set(参数)_________没有返回值____接收参数
JavaBean中类的属性是根据方法推断出的
内省:
PropertyDescriptor类的应用
通过符合规则的JavaBean类和属性名,反射方法,从而得到获取和修改该属性名的值的方法,调用invoke调用方法
需要注意的是,为了使程序达到更好的复用性,应该将代码重构,将常用的代码块包装成为方法
包装时类应该采用Object类达到跟好的复用性
PropertyDescriptor pd = new PropertyDescriptor(属性名,类);
Method methodGet = pd.getReadMethod();
methodGet.invoke()
!!!注意JavaBean类 应该为public的 否则BeanUtils不能读取和修改里面的数据
Apache开源jar下载地址:
http://www.apache.org/dist//
测试
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
public class TestBean {
public static void main(String[] args) throws Exception{
Point1 p1 = new Point1(1,2);
Point1 p2 = new Point1(4,6);
//System.out.println(p1.getX());
String strname = "x";
Object retval = getProperty(p1, strname);
System.out.println(retval);
int val = 7;
setProperty(p1, strname, val);
System.out.println(BeanUtils.getProperty(p1, strname));
BeanUtils.setProperty(p1, strname, "10");
System.out.println(p1.getX());
}
public static void setProperty(Object p1, String strname, Object val)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(strname,p1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(p1,val);
}
public static Object getProperty(Object p1, String strname)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(strname,p1.getClass());
Object retval=null;
Method methodGetX = pd.getReadMethod();
retval = methodGetX.invoke(p1);
/*
BeanInfo beanInfo = Introspector.getBeanInfo(p1.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd3:pds){
if(pd3.getName().equals("strname")){
break;
}
}
*/
return retval;
}
}
JavaBean BeanUtils
最新推荐文章于 2021-02-13 07:05:46 发布