当前位置:网站首页>Tool class: object to map hump to underline underline hump

Tool class: object to map hump to underline underline hump

2022-07-07 06:57:00 Wandering elephant

package com.esint.gaplatform.sjxxdataxjclgs.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Obj2map {
    

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
    
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
    
            field.setAccessible(true);
            String fieldName = field.getName();
            String field_name = humpToLine(fieldName);
            Object value = field.get(obj);
            map.put(field_name, value);
        }
        return map;
    }

    private static Pattern linePattern = Pattern.compile("_(\\w)");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /** *  Hump underline , Finally capitalize  * @param str * @return */
    public static String humpToLine(String str) {
    
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
    
            matcher.appendReplacement(sb, "_" + matcher.group(0).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString().toUpperCase();
    }

    /** *  Underline to hump , Normal output  * @param str * @return */
    public static String lineToHump(String str) {
    
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
    
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


}

原网站

版权声明
本文为[Wandering elephant]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070240240795.html