随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

使用Java反射机制将Bean对象转换成Map(驼峰命名方式 — 下划线命名方式)

复制代码
package com.yunping.asap.core.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.Id;

import org.apache.commons.lang3.StringUtils;

/**
 * 使用Java反射机制将Bean对象转换成Map(驼峰命名方式 —下划线命名方式)
 * 
 * @author admin
 *
 */
public class CamelUnderlineUtil {
    /**
     * 主键字段名
     */
    public static final String PK ="pk";
    private static final char UNDERLINE ='_';
    /**
     * 驼峰命名转换成下划线方式名称,eg:cfConfigRecord > cf_config_record
     * 
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if (StringUtils.isEmpty(param)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        int len = param.length();
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    
    /**
     * 下划线方式名称转换成驼峰命名,eg:cf_config_record > cfConfigRecord
     * 
     * @param param
     * @return
     */
    public static String underlineToCamel(String param){
        if (StringUtils.isEmpty(param)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        int len = param.length();
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c==UNDERLINE) {
                if(++i<len){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    
    /**
     * Bean对象转Map方法<br/><br/>
     * 
     * eg、{pk=ccr_id, ccr_id=1, operate_type=1, create_time=2020-08-24 13:44:09, remark=测试测试, sql=aaa}
     * 
     * @param obj
     * @param clazz
     * @return
     * @throws Exception
     */
    public static Map<String, String> convertObjectToMap(Object obj, Class clazz) throws Exception {
        Map<String, String> dstMap = new HashMap<String, String>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("serialVersionUID".equals(field.getName())) {
                continue;
            }
            
            //获取主键字段
            boolean hasIdAannotation = field.isAnnotationPresent(Id.class);
            if (hasIdAannotation) {
                dstMap.put(PK, CamelUnderlineUtil.camelToUnderline(field.getName()));
            }
        
            String dstName = CamelUnderlineUtil.camelToUnderline(field.getName());
            PropertyDescriptor pd;
            pd = new PropertyDescriptor(field.getName(), clazz);
            Method method = pd.getReadMethod();
            Object dstObject = method.invoke(obj);
            if (dstObject instanceof Date) {
                dstObject = DateUtil.dateToString((Date)dstObject);
            }
            if (dstObject instanceof ArrayList) {
                dstObject = "";
            }
            dstMap.put(dstName, dstObject == null ? "" : dstObject.toString());
        }
        return dstMap;
    }
 
     
 
}
复制代码

 

复制代码
public class CamelUnderlineUtilTest {

    public static void main(String[] args) throws Exception {
        CfConfigRecord record = new CfConfigRecord();
        record.setCcrId("1");
        record.setSql("select * from cf_config_record limit 500");
        record.setOperateType(1);
        record.setCreateTime(new Date());
        record.setRemark("测试测试");
        Map<String, String> dataMap = CamelUnderlineUtil.convertObjectToMap(record, CfConfigRecord.class);
        System.out.println(dataMap);
    }
}
复制代码

 

posted on   Ruthless  阅读(2102)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
历史上的今天:
2017-08-24 Mysql 查看连接数,状态 最大并发数
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示