BeanUtils封装对象数据

BeanUtils主要解决的是,把对象的属性数据封装到对象中。
在J2EE的编程过程中,我们经常从各种配置文件中读取相应的数据。



在配置文件中读取到的数据都是String。因此,我们都会需要将字符串类型转换成其他的数据类型。一般我们需要判断数据类型,然后对字符串类型调用相应的转换方法去转换成我们想要的类型。但是,很明显这些步骤很繁琐。所以,我们可以使用BeanUtils工具来将从配置文件中读取出来的数据,封装到对象当中。


1、使用BeanUtils工具,是需要导入BeanUtils的相关jar包的。可以到官方网站下载: Apache Commons BeanUtils 1.9.3
2、其中BeanUtils还依赖于log4J的相关jar包。可以到官方网站下载 Apache log4j
3、还需要commons-logging.jar包,可以到
mvnrepository 可以寻找到许多jar包。




一、设置javabean的属性参数
二、拷贝javabean到另外一个javabean对象中(也可以将map集合中的数据拷贝到一个javabean当中)


一、设置javabean的属性参数

package com.descriptor;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

/**
 * Description:
 * 当我们学习框架的时候,是需要将数据从xml文件(配置文件)读取出来并将其封装在一个对象当中。
 * 而使用内省来封装数据过于繁琐。
 * 这里,我们使用BeanUtils将数据封装在一个对象中。
 * 
 * @author lee
 * */
public class BeanUtilsDemo {

    /**
     * Description:
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * 
     * 
     * */
    public static void test1() 
            throws IllegalAccessException, InvocationTargetException{

        //这里省略了将数据从xml文件(配置文件)读取出来步骤。
        //关于如何从xml文件读取数据,可以查看我的另外一篇博客---使用dom4j解析xml文件。
        String id = "1";
        String name = "lee";
        String birthday = "1993-02-24";
        Student student1 = new Student();

        //(1)BeanUtils 设置属时,如果属性时基本数据类型,BeanUtils会自动帮我转换类型。
        //一般,我们从配置文件中读取的数据都为String类型,因此有了BeanUtils会省却了很多步骤。
        //(其底层还是依赖着内省,因此封装数据的对象需要所有数据的getter和setter方法)

        //因此不管id和name是什么基本数据类型,是不需要理会的
        BeanUtils.setProperty(student1, "id", id);
        BeanUtils.setProperty(student1, "name", name);
        //and don't project it all do anyone know.


        //(2)当属性为引用类型的时候,我们需要注册一个类型转换器

        //因此Student的数据birthday是属于Date的引用类型,我们需要注册一个转换器
        ConvertUtils.register(new Converter(){

            @SuppressWarnings("unchecked")
            @Override
            public <T> T convert(Class<T> type, Object value) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date = dateFormat.parse((String)value);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                return (T) date;
            }

        }, Date.class);

        //为引用类型设置值
        BeanUtils.setProperty(student1, "birthday", birthday);

        System.out.println(student1);



    }

    /**
     * Description:
     * 主方法
     * 
     * */
    public static void main(String[] args)throws Exception {
        test1();
    }

}



javabean的代码:

package com.descriptor;

import java.util.Date;

/**
 * Description:
 * 一个人类
 * The class must be public, and provide a public constructor that accepts no arguments. 
 * This allows tools and applications to dynamically create new instances of your bean, 
 * without necessarily knowing what Java class name will be used ahead of time.
 * 
 * @author lee
 * */
public class Student{
    //id
    private int id;
    //名字
    private String name;
    //生日
    private Date birthday;

    /**
     * Description:
     * 默认构造器
     * 
     * */
    public Student(){}

    /**
     * Description:
     * 初始化id name birthday的构造器
     * 
     * @param id id
     * @param name 名字
     * @param birthday 生日
     * */
    public Student(int id, String name, Date birthday){
        this.id = id;
        this.name = name;
        this.birthday = birthday;

    }

    /**
     * Description:
     * 重写了toString方法
     * 
     * */
    @Override
    public String toString(){
        return "id = "+id+", name = "+name+", birthday  = "+birthday;
    }

    //getter,setter方法
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }


}





二、拷贝javabean到另外一个javabean中(也可以将map集合中的数据拷贝到一个javabean当中)

package com.descriptor;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

/**
 * Description:
 * 当我们学习框架的时候,是需要将数据从xml文件(配置文件)读取出来并将其封装在一个对象当中。
 * 而使用内省来封装数据过于繁琐。
 * 这里,我们使用BeanUtils将数据封装在一个对象中。
 * 
 * @author lee
 * */
public class BeanUtilsDemo {

    /**
     * Description:
     * 使用BeanUtils将对象的属性数据copy到另外一个对象当中。
     * @throws ParseException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * 
     * */
    public static void test2() throws ParseException, IllegalAccessException, InvocationTargetException{

        //一、拷贝javabean到另外一个javabean对象中
        //创建一个对象,初始化它的成员变量
        Student s1 = new Student(1,"lee",new SimpleDateFormat("yyyy-MM-dd").parse("1991-04-23"));
        Student s2 = new Student();

        /*
        这里我尝试着,像从xml文件中读取的数据那样,将代表日期String类型,转换成Date类型。
        但是,此时我们是把数据从另外一个 对象copy到另外一个对象当中.
        因此,日期是不需要类型转换的。当把下面的的convertor的注释去掉的话,
        就会出现 java.util.Date cannot be cast to java.lang.String报错。
        甚至,这个convertor都不需要注册。
        */
        ConvertUtils.register(new Converter(){

            @SuppressWarnings("unchecked")
            @Override
            public <T> T convert(Class<T> type, Object value) {
//              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//              Date date = null;
//              try {
//                  date = dateFormat.parse((String)value);
//              
//              } catch (ParseException e) {
//                  System.out.println("??");
//                  e.printStackTrace();
//              }

                return (T) value;
            }

        }, Date.class);

        //将s1的数据复制到s2中
        BeanUtils.copyProperties(s2, s1);
        System.out.println(s2);



        //二、将map集合中的数据拷贝到一个javabean
        Student s3 = new Student();

        //创建一个hashmap集合,放进 需要封装到javabean的数据
        Map<String, Object> data = new HashMap<>();
        data.put("id", 1);
        data.put("name","wang");
        data.put("birthday",new SimpleDateFormat("yyyy-MM-dd").parse("1991-04-23"));

        //从Map集合copy到s3对象当中
        BeanUtils.copyProperties(s3, data);
        System.out.println(s3);
    }

    /**
     * Description:
     * 主方法
     * 
     * */
    public static void main(String[] args)throws Exception {
        test2();
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值