Map和Bean互转(Java)

1. map转bean

今天要写一个Map转Bean的,忘记了原来写的时候用的什么类,百度了很多也没找到,废了九牛二虎之力找到了,Mark一下,以备之后使用。

import org.apache.commons.beanutils.ConvertUtils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
//导入的核心包
public class TransUtils{

    public static <T> T mapToDomain(Map<String, Object> map, Class<T> tClass) {
        try {
            T t = tClass.newInstance();

            BeanInfo beanInfo = Introspector.getBeanInfo(tClass);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {

                String key = property.getName();
                if ("class".equals(key)) {
                    continue;
                }

                String sqlField = CamelAndLowerUpperTrans.camelToUnderscore(key);


                if (map.containsKey(sqlField)) {

                    try {
                        Object value = map.get(sqlField);
                        // 得到property对应的setter方法
                        Method setter = property.getWriteMethod();
                        Class<?> type = property.getPropertyType();
                        // 强转为字段的类型,不需要时可以去除,依赖commons-beanutilss-beanutils
                        //Object convert = ConvertUtils.convert(String.valueOf(value), type);
                        //setter.invoke(t, convert);
                        setter.invoke(t, value);
                    } catch (Exception e) {
                        throw new RuntimeException("【赋值异常】", e);
                    }
                }

            }

            return t;
        } catch (Exception e) {
            throw new RuntimeException("【Map转换实体异常】", e);
        }
    }
}

其中驼峰和下划线格式命令互转的工具类如下(Mysql字段和Bean的属性名定义不一致,如:sound_avg与soundAvg的互转)

public class CamelAndLowerUpperTrans {

    public static String underscoreToCamel(String name) {
        StringBuilder sb = new StringBuilder();
        String[] splits = name.split("_");
        String part;
        for (int i = 0; i < splits.length; i++) {
            part = splits[i];
            if( i > 0) {
                part = part.substring(0, 1).toUpperCase() + part.substring(1);
            }
            sb.append(part);
        }

        return sb.toString();
    }

    public static String camelToUnderscore(String name) {
        if (name == null && name.length() <= 0) {
            return name;
        }
        StringBuilder sb = new StringBuilder();
        String lowerName = name.toLowerCase();
        for (int i = 0; i < lowerName.length(); i++) {
            String nameChar = name.substring(i, i + 1);
            String lowerChar = lowerName.substring(i, i + 1);
            if (!nameChar.equals(lowerChar)) {
                sb.append("_").append(lowerChar);
            } else {
                sb.append(nameChar);
            }
        }

        return sb.toString();
    } 

    public static void main(String[] args) {
        System.out.println(CamelAndLowerUpperTrans.camelToUnderscore("soundMinAvg"));
    }
}

2. bean转map

将bean的中所有属性转为map,包括继承自父类的属性

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class BeanUtils {
    
    private BeanUtils() {
    }

    /**
     * 将bean转为Map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> beanToMap(Object object) {
        Map<String, Object> result = new HashMap<>();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String fieldName = propertyDescriptor.getName();
                if ("class".equals(fieldName)) {
                    continue;
                }

                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(object);

                result.put(fieldName, value);
            }


            return result;
        } catch (Exception e) {
            throw new RuntimeException("读取bean属性失败", e);
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值