zoukankan      html  css  js  c++  java
  • 将对象转成map 类型的key 和value

    package com.bnl.core.util;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * java 对象转换为Map key-value形式
     * @author:libaoneng
     * @date 2019-10-15 13:07
     **/
    public class ObjectToMap {
        /**
         * 将一个类查询方式加入map(属性值为int型时,0时不加入,
         * 属性值为String型或Long时为null和“”不加入)
         *注:需要转换的必须是对象,即有属性
         */
        public static Map<String, Object> setConditionMap(Object obj){
            Map<String, Object> map = new HashMap<>();
            if(obj==null){
                return null;
            }
            Field[] fields = obj.getClass().getDeclaredFields();//获取类的各个属性值
            for(Field field : fields){
                String fieldName =  field.getName();//获取类的属性名称
                if(getValueByFieldName(fieldName,obj)!=null)//获取类的属性名称对应的值
                    map.put(fieldName,  getValueByFieldName(fieldName,obj));
            }
            return map;
        }
        /**
         * 根据属性名获取该类此属性的值
         * @param fieldName
         * @param object
         * @return
         */
        public static Object getValueByFieldName(String fieldName,Object object){
            String firstLetter=fieldName.substring(0,1).toUpperCase();
            String getter = "get"+firstLetter+fieldName.substring(1);
            try {
                Method method = object.getClass().getMethod(getter, new Class[]{});
                Object value = method.invoke(object, new Object[] {});
                return value;
            } catch (Exception e) {
                return null;
            }
        }
    }
  • 相关阅读:
    多屏共享
    md5-linux_shell
    2017年会所得
    linux无线网络配置_转
    (转)台式机华硕主板双显卡切换,怎么舒服怎么来
    Apache FtpServer 实现文件的上传和下载
    (转载)Windows 上搭建Apache FtpServer
    Eclipse常用设置
    博客园文章样式修改
    黑马公社学习
  • 原文地址:https://www.cnblogs.com/yishuo/p/13033654.html
Copyright © 2011-2022 走看看