zoukankan      html  css  js  c++  java
  • Java的Map和Object之间的相互转换方法

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

      

  • 相关阅读:
    java类型比较_Java数据类型的比较
    学习方法-1:海绵学习法
    性能测试:TPS和QPS的区别
    代码反思
    网站TLS升级 1.0&1.1--1.2
    Mysql常用语法
    初级测试工程师面试指南
    postman实战之断言
    postman预处理脚本实战
    什么是HTTP超文本协议
  • 原文地址:https://www.cnblogs.com/myyBlog/p/9400877.html
Copyright © 2011-2022 走看看