JavaBean 對象與 Map的糾紛

今天有點兒閒,蛋蛋分享個JavaBean 對象與 Map的轉換:
<!--BeanToMap1-->
 public static Map<String, Object> bean1(Object bean) throws Exception {
        Class<? extends Object> type = bean.getClass();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        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;
    }


<!--BeanToMap2-->
    public static Map<String, Object> BeantoMap(Object obj) {  
        if(obj == null){  
            return null;  
        }          
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();    
                if (!key.equals("class")) {  
                    // 得到property對應的getter方法  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
                    map.put(key, value);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("transBean2Map Error " + e);  
        }  
        return map;  
    }


<!--MapToBean-->
    public static Object map(Class<?> type, Map<?, ?> map) throws Exception {
        Object obj = type.newInstance(); // 創建 JavaBean 對象
        Field[] fields  = obj.getClass().getDeclaredFields();
        for(Field field : fields){
            String fieldName = field.getName();
            if(map.containsKey(fieldName)){
                field.set(obj, map.get(fieldName));
            }
        }
        return obj;
    }

歡迎大家支持蛋蛋,歡迎加入蛋蛋的QQ羣:214262473 Java技術交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章