| 一直不清楚beanUtils是怎样做到将Map和java bean的数据相互copy的。今天看了一下common-beanUtils代码发现他们用了一些以前我不知道的但又是jdk中含有的java.beans包下面的几个class来完成这个功能的。
 其中主要有java.beans.Introspector和java.beans.BeanInfo和java.beans.PropertyDescriptor。
 
 beanutils先将Map中的key定义成java bean中的属性名称,然后通过属性找到属性的写方法和读方法。
 这样就可以轻易完成这个Map到java bean的数据copy功能了。
 
 下面的代码说明了一下java.beans的几个class的使用。
 
 package hello;
 import java.beans.Introspector;import java.beans.BeanInfo;
 import java.beans.PropertyDescriptor;
 import java.util.Enumeration;
 public class HelloJSPBean{
 private String sample = "Start value";
     private String sample2 = "Start value";     //Access sample propertypublic String getSample()
 {
 System.out.println("getSample()");
 return sample;
 }
     //Access sample propertypublic void setSample(String newValue)
 {
 System.out.println("setSample()");
 if (newValue!=null)
 {
 sample = newValue;
 }
 }
     public static void main(String[] args) throws Exception{HelloJSPBean bean = new HelloJSPBean();
 BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
 PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();
 for (int i = 0 ; i < ps.length ; i++){
 System.out.println(ps[i]+"-----------");
 System.out.println(ps[i].getDisplayName());
 System.out.println(ps[i].getName());
 System.out.println(ps[i].getShortDescription());
 System.out.println(ps[i].getPropertyType());
 System.out.println(ps[i].getPropertyEditorClass());
 System.out.println(ps[i].getReadMethod());
 System.out.println(ps[i].getWriteMethod());
 Enumeration em = ps[i].attributeNames();
 while (em.hasMoreElements()){
 System.out.println("name : " + em.nextElement());
 System.out.println("value : " + ps[i].getValue((String)em.nextElement()));
 }
 }
 }
 public String getSample2() {
 return sample2;
 }
 }
 
 |