[java] HashMap 과 Bean 의 상호 전환

4867 단어
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * HashMap Bean     
 * 
 * @author hailan
 * @time 2015-10-12  05:56:34
 */
public class HashMapBeanTools {
	
	/**
	 * HashMap   JavaBean
	 * 
	 * @author hailan
	 * @time   05:57:16
	 * @param map
	 * @param cls
	 * @return
	 */
	public static Object hashMapToJavaBean(HashMap<?,?> map, Class<?> cls) {
		Object obj = null;
		try {
			obj = cls.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//   bean      
		Method[] methods = cls.getMethods();
		for (int i = 0; i < methods.length; i++) {
			//     
			String method = methods[i].getName();
			//        
			Class<?>[] cc = methods[i].getParameterTypes();
			if (cc.length != 1)
				continue;

			//         set        for
			if (!method.startsWith("set") )
				continue;
			//   
			String type = cc[0].getSimpleName();

			try {
				//
				Object value = method.substring(3,4).toLowerCase().concat(method.substring(4));
				//   map   key
				if (map.containsKey(value)) {
					//        
					setValue(type, map.get(value), i, methods, obj);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	/**
	 *          
	 * 
	 * @author hailan
	 * @time   06:01:56
	 * @param type
	 * @param value
	 * @param i
	 * @param method
	 * @param bean
	 * @throws Exception 
	 */
	private static void setValue(String type, Object value, int i, Method[] method,
			Object bean) throws Exception {
		if (value != null && !value.equals("")) {
			try {
				if (type.equals("String")) {
					//      :                 :         
					method[i].invoke(bean, new Object[] { value });
				} else if (type.equals("int") || type.equals("Integer")) {
					method[i].invoke(bean, new Object[] { new Integer(""
							+ value) });
				} else if (type.equals("BigDecimal")) {
					method[i].invoke(bean, new Object[] { new BigDecimal((String)value) });
				} else if (type.equals("long") || type.equals("Long")) {
					method[i].invoke(bean,
							new Object[] { new Long("" + value) });
				} else if (type.equals("boolean") || type.equals("Boolean")) {
					method[i].invoke(bean, new Object[] { Boolean.valueOf(""
							+ value) });
				} else if (type.equals("Date")) {
					Date date = null;
					if (value.getClass().getName().equals("java.util.Date")) {
						date = (Date) value;
					} else {
						//            ,                。
						if (value.toString().length() > 10){
							String format = "yyyy-MM-dd HHmmss";
							date = parseDateTime("" + value, format);
						} else if (value.toString().length() == 10){
							String format = "yyyy-MM-dd";
							date = parseDateTime("" + value, format);
						} else  if (value.toString().length() == 8){
							String format = "yyyyMMdd";
							date = parseDateTime("" + value, format);
						} else  if (value.toString().length() == 14){
							String format = "yyyyMMddHHmmss";
							date = parseDateTime("" + value, format);
						}else  if (value.toString().length() == 6){
							String format = "HHmmss";
							date = parseDateTime("" + value, format);
						}
					}
					if (date != null) {
						method[i].invoke(bean, new Object[] { date });
					}
				} else if (type.equals("byte[]")) {
					method[i].invoke(bean,
							new Object[] { new String(value + "").getBytes() });
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
	}

	/**
	 *       
	 * 
	 * @author hailan
	 * @time   06:02:59
	 * @param dateValue
	 * @param format
	 * @return
	 */
	private static Date parseDateTime(String dateValue, String format) {
		SimpleDateFormat obj = new SimpleDateFormat(format);
		try {
			return obj.parse(dateValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public static Map<String, Object> hashJavaBeanToMap(Object ojt) {
		Class<?> cls = ojt.getClass();
		Field[] field = cls.getDeclaredFields();   
		  
        HashMap<String, Object> mapbean = new HashMap<String, Object>();   
        for(int i=0;i<field.length;i++){   
            Field f = field[i];   
            f.setAccessible(true);   
            try {   
            	mapbean.put(f.getName(), f.get(cls));   
            } catch (IllegalArgumentException e) {   
                e.printStackTrace();   
            } catch (IllegalAccessException e) {   
                e.printStackTrace();   
            }   
        }   
		return mapbean;   
    }   

	
}

좋은 웹페이지 즐겨찾기