学习common-beanUtils的基本工作原理

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

一直不清楚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 property

public String getSample()

{

System.out.println("getSample()");

return sample;

}

//Access sample property

public 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;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航