map转bean工具类

该代码片段展示了如何利用Apache Commons BeanUtils库将Map对象转换为指定类型的Java Bean。它注册了一个自定义转换器,将字符串转换为日期,并处理了转换过程中的异常。如果Map为空,则返回null;否则,创建并填充指定类的新实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

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



public class MapToBeanUtils {
	/**
	 * 
	 * mapToObject:map转bean. <br/>
	 *
	 * @author jackl Date:2017年4月18日下午6:15:49
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)   {
		ConvertUtils.register(new Converter(){  
            @SuppressWarnings("rawtypes")
            @Override
            public Object convert(Class arg0, Object arg1){
                System.out.println("注册字符串转换为date类型转换器");
                if(arg1 == null){
                    return null;
                }
                if(!(arg1 instanceof String)){
                    throw new ConversionException("只支持字符串转换 !");
                }
                String str = (String)arg1;
                if(str.trim().equals("")){
                    return null;
                }  
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                try{
					return sd.parse(str);
                }catch(ParseException e) {
                	 try {
                		 sd = new SimpleDateFormat("yyyy-MM-dd");  
						return sd.parse(str);
					} catch (ParseException e1) {
						throw new RuntimeException(e);
					}
                }  
            }  

        }, java.util.Date.class);
		
		if (map == null)
			return null;
		Object obj = null;
		try {
			obj = beanClass.newInstance();
			org.apache.commons.beanutils.BeanUtils.populate(obj, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值