Java tutorial
/* * Copyright 2013 zhangyue.com All right reserved. This software is the * confidential and proprietary information of Renren.com ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with zhangyue.com. */ package com.zhangyue.zeus.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Mapbean * * @date 2013-9-6 * @author rongneng */ public class BeanUtils { private final static Log LOG = LogFactory.getLog(BeanUtils.class); /** * ?mapkey?? */ private static final String OMIT_REG = "_"; /** * map???Bean?Bean??mapkey??mapkey?OMIT_REG? * * @param <E> * @param cla * @param mapList * @return */ public static <E> List<E> toBeanList(Class<E> cla, List<Map<String, Object>> mapList) { List<E> list = new ArrayList<E>(mapList.size()); for (Map<String, Object> map : mapList) { E obj = toBean(cla, map); list.add(obj); } return list; } /** * map??BeanBean??mapkey??mapkey?OMIT_REG? * * @param <E> * @param cla * @param map * @return */ @SuppressWarnings({ "rawtypes" }) public static <E> E toBean(Class<E> cla, Map<String, Object> map) { // E obj = null; try { obj = cla.newInstance(); if (obj == null) { throw new Exception(); } } catch (Exception e) { LOG.error(",:" + cla); return null; } // ?mapkey Map<String, Object> newmap = new HashMap<String, Object>(); for (Map.Entry<String, Object> en : map.entrySet()) { newmap.put("set" + en.getKey().trim().replaceAll(OMIT_REG, "").toLowerCase(), en.getValue()); } // Method[] ms = cla.getMethods(); for (Method method : ms) { String mname = method.getName().toLowerCase(); if (mname.startsWith("set")) { Class[] clas = method.getParameterTypes(); Object v = newmap.get(mname); if (v != null && clas.length == 1) { try { method.invoke(obj, v); } catch (Exception e) { LOG.error("," + cla + "." + method.getName() + ".?" + clas[0] + ";:" + v.getClass()); } } } } return obj; } }