Map与JavaBean互相转换工具类(反射和内省手工实现)

文章介绍了两种方法,一种是使用反射和`Field`,另一种是利用JavaBeans的内省机制,分别实现将JavaBean对象转换为Map以及Map转换回JavaBean对象的过程。
摘要由CSDN通过智能技术生成

反射方式实现

 import com.wc.domain.User;
 ​
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 ​
 /**
  * @author JngKang
  * @date 2022-04-18 12:16
  * @description Map与JavaBean相互转换工具类
  */
 public class MapBeanUtil {
 ​
     /**
      * @param obj 待转化的实体对象
      * @return java.util.Map<java.lang.String,java.lang.Object>
      * @description 将实体对象转化为HashMap
      */
     public static Map<String, Object> bean2Map(Object obj) {
         Map<String, Object> map = new LinkedHashMap<>();
         Class<?> clazz = obj.getClass();
 ​
         for (Field field : clazz.getDeclaredFields()) {
             field.setAccessible(true);
             String fieldName = field.getName();
             Object value = null;
             try {
                 value = field.get(obj);
             } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
             if (value == null){
                 value = "";
             }
             map.put(fieldName, value);
         }
         return map;
     }
 ​
     /**
      * @param map   待转化数组
      * @param clazz 转化的实体
      * @return T 返回相应的实体
      * @description 使用反射中内省的方式将map中的数据转化为相应的实体
      */
     public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) {
         if (map == null) {
             return null;
         }
         T res = null;
         try {
             res = clazz.getDeclaredConstructor().newInstance();
             //获取到所有属性,不包括继承的属性
             Field[] fields = clazz.getDeclaredFields();
             for (Field field : fields) {
                 //获取字段的修饰符
                 int mod = field.getModifiers();
                 if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                     continue;
                 }
                 //设置对象的访问权限
                 field.setAccessible(true);
                 //根据属性名称去map获取value
                 if(map.containsKey(field.getName())) {
                     //给对象赋值
                     field.set(res, map.get(field.getName()));
                 }
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return res;
     }
 ​
     public static void main(String[] args) throws Exception {
         Map<String, Object> map = new HashMap<>();
         map.put("id", 10000L);
         map.put("name", "wwk");
         map.put("gender", true);
         map.put("email", "asf");
         map.put("tel", "123");
         map.put("credits", 100);
         map.put("status", 3);
         User user = map2Bean(map, User.class);
         System.out.println(user);
         Map<String, Object> res = bean2Map(user);
         res.forEach((k, v) -> System.out.println(k + " - " + v));
     }
 }

内省方式实现

 import com.wc.domain.User;
 ​
 import java.beans.BeanInfo;
 import java.beans.IntrospectionException;
 import java.beans.Introspector;
 import java.beans.PropertyDescriptor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.Map;
 ​
 /**
  * @author JngKang
  * @date 2022-04-18 09:19
  * @description Map与JavaBean相互转换工具类
  */
 public class BeanMapTransUtil {
 ​
     /**
      * @param map   待转化数组
      * @param clazz 转化的实体
      * @return T 返回相应的实体
      * @description 使用反射中内省的方式将map中的数据转化为相应的实体
      */
     public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IntrospectionException {
         T obj = clazz.getDeclaredConstructor().newInstance();
         // 根据clazz获取BeanInfo
         BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
         // 获取所有成员变量名
         PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
         // 遍历
         for (PropertyDescriptor pd : pds) {
             // 获取Setter方法
             Method writeMethod = pd.getWriteMethod();
             // 获取成员变量名,并为其赋值
             writeMethod.invoke(obj, map.get(pd.getName()));
         }
         return obj;
     }
 ​
     /**
      * @param obj 待转化的实体对象
      * @return java.util.Map<java.lang.String,java.lang.Object>
      * @description 将实体对象转化为HashMap
      */
     public static Map<String, Object> bean2Map(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
         Map<String, Object> map = new HashMap<>();
         // 获取实体对象的字节码文件
         Class<?> clazz = obj.getClass();
         // 获取BeanInfo
         BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
         // 获取所有的成员变量名
         PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
         // 遍历
         for (PropertyDescriptor pd : pds) {
             // 获取成员变量名
             String field = pd.getName();
             // 获取Getter方法
             Method readMethod = pd.getReadMethod();
             // 获取成员变量的值
             Object value = readMethod.invoke(obj);
             // 存入map
             map.put(field, value);
         }
         return map;
     }
 ​
     public static void main(String[] args) throws IntrospectionException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
         Map<String, Object> map = new HashMap<>();
         map.put("id", 10000L);
         map.put("name", "wwk");
         map.put("gender", true);
         map.put("email", "asf");
         map.put("tel", "123");
         map.put("credits", 100);
         map.put("status", 3);
         User user = map2Bean(map, User.class);
         System.out.println(user);
         Map<String, Object> res = bean2Map(user);
         res.forEach((k, v) -> System.out.println(k + " - " + v));
     }
 }

测试中使用的实体:

 import lombok.AllArgsConstructor;
 import lombok.Builder;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
 import lombok.ToString;
 ​
 /**
  * @author JngKang
  * @date 2022-04-02 15:47
  * @description
  */
 @Setter
 @Getter
 @NoArgsConstructor
 @AllArgsConstructor
 @Builder
 @ToString
 public class User {
     private Long id;
     private String name;
     private Boolean gender;
     private String email;
     private String tel;
     private Integer credits;
     private Integer status;
 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Apache Commons BeanUtils库来实现MapJavaBean的操作。该库提供了方便的工具类,可以简化这个过程。 首先,你需要将Apache Commons BeanUtils库添加到你的项目中。你可以在Maven项目中添加以下依赖: ```xml <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency> ``` 然后,你可以创建一个工具类,其中包含一个静态方法来执行MapJavaBean转换。下面是一个示例: ```java import org.apache.commons.beanutils.BeanUtils; public class MapToBeanConverter { public static <T> T convertMapToBean(Map<String, Object> map, Class<T> beanClass) { try { T bean = beanClass.getDeclaredConstructor().newInstance(); BeanUtils.populate(bean, map); return bean; } catch (Exception e) { // 处理异常 e.printStackTrace(); return null; } } } ``` 在上述代码中,`convertMapToBean`方法接受一个`Map<String, Object>`和目标JavaBean的Class对象作为参数。它使用BeanUtils类的`populate`方法将Map中的键值对设置到JavaBean对象中。 使用该工具类,你可以将一个Map转换为对应的JavaBean对象。示例如下: ```java Map<String, Object> map = new HashMap<>(); map.put("property1", "value1"); map.put("property2", 123); JavaBean bean = MapToBeanConverter.convertMapToBean(map, JavaBean.class); ``` 在上述示例中,我们创建一个包含属性名和对应值的Map对象,并将其传递给`convertMapToBean`方法。它将返回一个JavaBean对象,其中的属性值已经被设置。 希望这个工具类对你有帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值