平时我们常会遇到Bean对象和Map的转换,对于字段比较少并且结构简单的Bean对象和Map的转换,常规做法就是逐个去set属性和值,或者逐个put属性和值,但是如果对于字段比较多或者嵌套结构复杂的Bean对象和Map转换,常规做法就远远力不从心了,那么我们就需要封装一个公共的高效的泛型工具类去进行转换。笔者结合平时的编码经验积累,经过整理,本案例给大家分享5种方式实现Bean对象和Map的转换,本案例基于BeanUtils.populate(bean, map)和JDK自带的反射机制,废话不多时,直接上代码。
准备工作:先在pom文件中添加org.apache.commons的依赖,如下所示:
commons-beanutils
commons-beanutils
工具类的5种具体实现方式:
package com.shsc.base.data.common.utils;
import org.apache.commons.beanutils.BeanUtils;
import com.shsc.base.data.common.mapper.entity.CustomerProduct;
import com.shsc.base.data.common.mapper.entity.ProductPic;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException