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);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值