天天看點

java map轉bean

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

            System.out.println(propertyName);

            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;  

    }