您的位置:首页 > 其它

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

2004-12-04 22:45 246 查看
作者game.19xz 来源19xz.com

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: