1. 程式人生 > >Map轉為Bean,註冊String轉Date

Map轉為Bean,註冊String轉Date

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 BeanUtils {

    public static void transMap2Bean(Map<String, Object> map, Object obj) {  
        
//ConvertUtils.register(new DateLocaleConverter(), Date.class); ConvertUtils.register(new Converter() { @SuppressWarnings("rawtypes") 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) { throw new RuntimeException(e); } } }, java.util.Date.class); if (map == null || obj == null) { return; } try { org.apache.commons.beanutils.BeanUtils.populate(obj, map); } catch (Exception e) { System.out.println("Map<String,Object>轉化Bean異常:" + e); } } }