1. 程式人生 > >Object Bean 轉為 map

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