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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值