1. 程式人生 > >java bean 與map之間的轉換

java bean 與map之間的轉換

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class CommonUtils {

	/**
	 * @author wangzj
	 * java bean轉map
	 * @param object
	 * @return
	 */
	public static final Map<String, Object> bean2Map(Object object) {
		Map<String, Object> beanMap = new HashMap<String, Object>();
		Class<? extends Object> clazz = object.getClass();
		List<Field> fields = new ArrayList<Field>();
		setFields(clazz, fields);
		for (Field field : fields) {
			field.setAccessible(true);
			String fieldName = field.getName();
			Object fieldValue = null;
			String getMethodName = "get" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1);
			try{
				Method method = clazz.getMethod(getMethodName);
				method.setAccessible(true);
				try {
					fieldValue = method.invoke(object);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}catch (NoSuchMethodException e){
				try {
					fieldValue = field.get(object);
				} catch (IllegalArgumentException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				}
			}
			beanMap.put(fieldName, fieldValue);
		}
		
		return beanMap;
	}
	
	private static void setFields(Class<? extends Object> clazz, List<Field> fields){
		Field[] declaredFields = clazz.getDeclaredFields();
		if(declaredFields != null && declaredFields.length != 0){
			for (int i = 0; i < declaredFields.length; i++) {
				fields.add(declaredFields[i]);
			}
		}
		Class<?> superclass = clazz.getSuperclass();
		if(clazz.getSuperclass() == null)
			return;
		setFields(superclass, fields);
		Class<?>[] interfaces = clazz.getInterfaces();
		if(interfaces == null)
			return;
		for (Class<?> inte : interfaces) {
			setFields(inte, fields);
		}
	}
}