一.javaBean用法
主要用于传递数据信息,这种java类中的方法主要用于访问私有的字段,且方法名符合某种命名规则
用 途:如果要在两个模块之间传递多个信息,可以将这些信息封装到一个JavaBean中,这种JavaBean的实例对象通常称之为值对象(Value Object,简称VO)。这些信息在类中用私有字段来存储,如果读取或设置这些字段的值,则需要通过一些相应的方法来访问。
特 点:JavaBean的属性是根据其中的setter和getter方法来确定的,而不是根据其中的成员变量。去掉set和get前缀,剩余部分就是属性名
JDK提供的对JavaBean进行操作的API,就被称为内省,avaAPI文档中的java.beans包和java.beans.beancontext
eg:
public static void setProperty(Object pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor dp1 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = dp1.getWriteMethod();
methodSetX.invoke(pt1,value);
}
eg:
public static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor dp = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = dp.getReadMethod();
Object retVal = methodGetX.invoke(pt1);
return retVal;
}
eg;
ReflectPoint pt1 = new ReflectPoint(1,1);
String propertyName = "x";
Object retVal = getProperty(pt1, propertyName);
System.out.println("getX:"+retVal);
Object value = 7;
setProperty(pt1, propertyName, value);
System.out.println("setX:"+pt1.getX());
用java.beans包中的PropertyDescriptor类操作javaBean
eg:
用BeanInfo类和IntroSpector类操作javaBean
eg:
public static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
PropertyDescriptor[] dps = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor dp:dps)
{
if(dp.getName().equals(propertyName)){
retVal = dp.getReadMethod().invoke(pt1);
break;
}
}
return retVal;
二.beanUtils工具包
eg:
ReflectPoint pt1 = new ReflectPoint(1,1);
BeanUtils.setProperty(pt1, "x", 25);
System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());
//BeanUtils可以实现属性链操作
BeanUtils.setProperty(pt1, "date.time", "111");//time不一定在类中存在,只是说明date有getTime和setTime方法。
System.out.println(BeanUtils.getProperty(pt1, "date.time"));
PropertyUtils.setProperty(pt1, "x", 160);
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());
BeanUtils:以字符串(String)的形式对JavaBean 的属性进行操作,getProperty方法得到的属性值是以字符串形式返回的(网络开发时,获取的用户数据类型都是String)。
PropertyUtils:以属性本身的类型最JavaBean的属性进行操作,getProperty()方法得到的属性值是以属性本来的类型返回的。