CommonUtil.java 987 Bytes
Newer Older
liqin's avatar
liqin committed
1
package cn.chnmuseum.party.common.util;
liqin's avatar
liqin committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

import java.util.Map;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

public class CommonUtil {

	/**
	 * 返回一个不重复的字符串
	 *
	 * @return
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().toLowerCase().replace("-","");
	}

	/**
	 * 把map转换成对象
	 * 
	 * @param map
	 * @param clazz
	 * @return
	 * 
	 * 		把Map转换成指定类型
	 */
	public static <T> T toBean(Map<String, ? extends Object> map, Class<T> clazz) {
		try {
			/*
			 * 1. 通过参数clazz创建实例 2. 使用BeanUtils.populate把map的数据封装到bean中
			 */
			T bean = clazz.newInstance();
			ConvertUtils.register(new DateConverter(), java.util.Date.class);
			BeanUtils.populate(bean, map);
			return bean;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}