zoukankan      html  css  js  c++  java
  • 通过反射将一个java对象的属性值转换为一个Map

    将一个java对象的属性值转换为一个Map:

     import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;

        public  Map<String, Object> transBean2Map(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();
    
                    // 过滤class属性
                    if (!"class".equals(key)) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        logger.info("获取到的getter为------>{}",getter);
                        Object value = getter.invoke(obj);
                        logger.info("获取到的key为----->{},value为----->{}",key,value);
                        map.put(key, value);
                    }
    
                }
            } catch (Exception e) {
                System.out.println("transBean2Map Error " + e);
                e.printStackTrace();
            }
    
            return map;
        }
  • 相关阅读:
    Spinal Tap Case
    Sorted Union
    Search and Replace
    Boo who
    Missing letters
    DNA Pairing
    Pig Latin
    Where art thou
    Roman Numeral Converter
    Redis高级客户端Lettuce详解
  • 原文地址:https://www.cnblogs.com/libin6505/p/11226552.html
Copyright © 2011-2022 走看看