Java对象转Map

  • Post author:
  • Post category:java


使用org.apache.commons.beanutils包下的BeanUtils.describe()方法可以将Java对象按属性转为Map。

import org.apache.commons.beanutils.BeanUtils;

class CommonUtils{
	public static Map<String, Object> convertToMap(Object obj) {
			try {
				if (obj instanceof Map) {
					return (Map)obj;
				}
				Map<String, Object> returnMap = BeanUtils.describe(obj);
				returnMap.remove("class");
				return returnMap;
			} catch (IllegalAccessException e1) {
				e1.getMessage();
			} catch (InvocationTargetException e2) {
				e2.getMessage();
			} catch (NoSuchMethodException e3) {
				e3.getMessage();
			}
			return new HashMap();
	}
}
@Test
public void test(){
	User user=new User();
	user.setName("aa");
	user.setSex(0);
	user.setAge(22);
	Map<String,Object> map=CommonUtils.convertToMap(user);
	System.out.println(JSONObject.toJSONString(map));
}



版权声明:本文为dongyuxu342719原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。