Object Bean 转为 map

简述:

将一个Bean对象转为map, 只转换一层嵌套的实现


实现:

	/**
	 * 将object 转换为map对象
	 * @param bean
	 * @return
	 * @throws IntrospectionException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	public static Map objectToMap(Object bean) 
			throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Map map = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
		for (PropertyDescriptor property : propertyDescriptors) {  
			String key = property.getName();  
			// 得到property对应的getter方法  
			Method getter = property.getReadMethod();
			Object value = getter.invoke(bean);
			map.put(key, value);
		}  
		return map;
	}


猜你喜欢

转载自blog.csdn.net/anialy/article/details/39896257