1. 程式人生 > >Java 中 Map與JavaBean之間的相互轉化

Java 中 Map與JavaBean之間的相互轉化

在做匯入的時候,遇到了需要將map物件轉化 成javabean的問題,也就是說,不清楚javabean的內部欄位排列,只知道map的 key代表javabean的欄位名,value代表值。

那現在就需要用轉化工具了。是通用的哦!

首先來看 JavaBean 轉化成Map的方法:

/**
     * 將一個 JavaBean 物件轉化為一個  Map
     * @param bean 要轉化的JavaBean 物件
     * @return 轉化出來的  Map 物件
     * @throws IntrospectionException 如果分析類屬性失敗
     * @throws IllegalAccessException 如果例項化 JavaBean 失敗
     * @throws InvocationTargetException 如果呼叫屬性的 setter 方法失敗
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map convertBean(Object bean)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }

下面是將Map轉化成JavaBean物件的方法:
/**
     * 將一個 Map 物件轉化為一個 JavaBean
     * @param type 要轉化的型別
     * @param map 包含屬性值的 map
     * @return 轉化出來的 JavaBean 物件
     * @throws IntrospectionException 如果分析類屬性失敗
     * @throws IllegalAccessException 如果例項化 JavaBean 失敗
     * @throws InstantiationException 如果例項化 JavaBean 失敗
     * @throws InvocationTargetException 如果呼叫屬性的 setter 方法失敗
     */
    @SuppressWarnings("rawtypes")
	public static Object convertMap(Class type, Map map)
            throws IntrospectionException, IllegalAccessException,
            InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type); // 獲取類屬性
        Object obj = type.newInstance(); // 建立 JavaBean 物件

        // 給 JavaBean 物件的屬性賦值
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                // 下面一句可以 try 起來,這樣當一個屬性賦值失敗的時候就不會影響其他屬性賦值。
                Object value = map.get(propertyName);

                Object[] args = new Object[1];
                args[0] = value;

                descriptor.getWriteMethod().invoke(obj, args);
            }
        }
        return obj;
    }

轉自:http://blog.csdn.net/chenxuejiakaren/article/details/7763061