160704、commons-beanutils.jar常用方法

package com.test.beanutils;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Test;
public class TestBeanUtils {
    /**BeanUtils.setProperty设置属性*/
    @Test
    public void test1() throws IllegalAccessException, InvocationTargetException{
        Person person = new Person();
        BeanUtils.setProperty(person, "age", 23);
        System.out.println(person.getAge());
    }
    /**BeanUtils.cloneBean克隆一个bean*/
    @Test
    public void test2() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
        Person person = new Person("lucy", 18, "xxxxx@qq.com");
        Person cloneBean = (Person) BeanUtils.cloneBean(person);
        System.out.println(cloneBean.toString());
    }
    /**注册转换器*/
    @Test
    public void test3() throws IllegalAccessException, InvocationTargetException{
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class type, Object value) {
                String str = (String) value;
                if(null == value){
                    return null;
                }
                if(!(value instanceof String)){
                    System.out.println("格式不正确");
                    return null;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = sdf.parse(str);
                    return parse;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }, Date.class);
        Person person = new Person();
        BeanUtils.setProperty(person, "birthday", "2016-07-01");
        System.out.println(person.getBirthday());
    }
    /**将map转换成bean并注册转换器*/
    @Test
    public void test4() throws IllegalAccessException, InvocationTargetException{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "test");
        map.put("birthday", "2016-07-01");
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        Person person = new Person();
        BeanUtils.populate(person, map);
        System.out.println(person.getBirthday());
    }
    /**转换器*/
    @Test
    public void test5(){
        Integer num = (Integer) ConvertUtils.convert("123", Integer.class);
        System.out.println(num);
    }
}

原文地址:https://www.cnblogs.com/zrbfree/p/5659845.html