zoukankan      html  css  js  c++  java
  • 8. Object转Map,Map转Object

       法一:使用reflect进行转换

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {    
        if (map == null)  
            return null;    
    Object obj = beanClass.newInstance(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { int mod = field.getModifiers(); if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){ continue; } field.setAccessible(true); field.set(obj, map.get(field.getName())); }
    return obj; } public static Map<String, Object> objectToMap(Object obj) throws Exception { if(obj == null){ return null; } Map<String, Object> map = new HashMap<String, Object>(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); map.put(field.getName(), field.get(obj)); } return map; }


    法二:使用Introspector进行转换
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {    
        if (map == null)   
            return null;    
     
        Object obj = beanClass.newInstance();  
      
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
        for (PropertyDescriptor property : propertyDescriptors) {  
            Method setter = property.getWriteMethod();    
            if (setter != null) {  
                setter.invoke(obj, map.get(property.getName()));   
            }  
        }  
      
        return obj;  
    }    
          
    public static Map<String, Object> objectToMap(Object obj) throws Exception {    
        if(obj == null)  
            return null;      
      
        Map<String, Object> map = new HashMap<String, Object>();   
      
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
        for (PropertyDescriptor property : propertyDescriptors) {    
            String key = property.getName();    
            if (key.compareToIgnoreCase("class") == 0) {   
                continue;  
            }  
            Method getter = property.getReadMethod();  
            Object value = getter!=null ? getter.invoke(obj) : null;  
            map.put(key, value);  
        }    
      
        return map;  
    }    
     
  • 相关阅读:
    c#之字符串,列表,接口,队列,栈,多态
    c#之函数
    KMP算法
    字符串Hash
    洛谷P1807 最长路_NOI导刊2010提高(07)
    洛谷P2863 [USACO06JAN]牛的舞会The Cow Prom
    洛谷P2071 座位安排
    二分图最大匹配,匈牙利算法
    差分约束系统
    搜索
  • 原文地址:https://www.cnblogs.com/zkx4213/p/8434671.html
Copyright © 2011-2022 走看看