新浪微博 Github

BeanUtils学习总结


一、BeanUtils介绍


BeanUtils是apache的开发库;

为了使用BeanUtils,需要导入

(1)common-logging-1.1.1.jar

(2)common-beanutils.jar


二、BeanUtils开发


(1)设置属性;
(2)注册转换器;
(3)自定义转换器;
(4)批量设置属性;

注意:JavaBean必须是public的,不然BeanUtils会抛异常;

package org.xiazdong.beanutils;

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.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Test;
import org.xiazdong.Person;

public class Demo01 {

	// 设置属性
	@Test
	public void test1() throws Exception {
		Person p = new Person();
		BeanUtils.setProperty(p, "name", "xiazdong");
		BeanUtils.setProperty(p, "age", 20);
		System.out.println(p.getName());
		System.out.println(p.getAge());
	}

	// 自定义转换器
	@Test
	public void test2() throws Exception {
		Person p = new Person();
		ConvertUtils.register(new Converter() {

			@Override
			public Object convert(Class type, Object value) {
				if (value == null) {
					return null;
				}
				if (!(value instanceof String)) {
					throw new ConversionException("conversion error");
				}
				String str = (String) value;
				if (str.trim().equals("")) {
					return null;
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					return sdf.parse(str);
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}

			}

		}, Date.class);
		BeanUtils.setProperty(p, "birth", "2011-10-10");
		System.out.println(p.getBirth().toLocaleString());
	}

	// 使用内置的转换器
	@Test
	public void test3() throws Exception {
		Person p = new Person();
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		BeanUtils.setProperty(p, "birth", "2011-10-10");
		System.out.println(p.getBirth().toLocaleString());
	}

	// 使用内置的转换器
	@Test
	public void test4() throws Exception {
		Map map = new HashMap();
		map.put("name", "xiazdong");
		map.put("age", "20");
		map.put("birth", "2010-10-10");
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		Person p = new Person();
		BeanUtils.populate(p, map);
		System.out.println(p.getAge());
		System.out.println(p.getBirth());
	}
}


posted @ 2012-03-10 14:16  xiazdong  阅读(196)  评论(0编辑  收藏  举报