Java对象和Map互相转换的6种方式

前言

开发小伙伴们通常会需要使用到对象和Map互相转换的开发场景,本文主要介绍6种方式,欲知详情,请问下文分解。

实体类:

@Data
class User {
    Long id;
    String name;
    Integer age;
}

1、hutool工具

官网:https://www.hutool.cn/

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

Hutool中的工具方法来自每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;
代码:

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.8.5</version>
</dependency>
public static void main(String[] args)  {
    User user= new User();
    user.setId(1L);
    user.setName("三省同学");
    //java转map
    System.out.println(BeanUtil.beanToMap(user));

//map转java
    Map<String, Object> map = new HashMap();
    map.put("id", 2L);
    map.put("name", "三省同学2");
    System.out.println(BeanUtil.toBean(map, User.class));
}
 
{id=1, name=三省同学, age=null}
User{id=2, name='三省同学2', age=null}

  
  
  • 1
  • 2

2、commons.beanutils工具

commons-beanutils是Apache开源组织提供的用于操作JAVABEAN的工具包。使用commons-beanutils,我们可以很方便的对bean对象的属性进行操作。

代码:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
	  <version>1.9.1</version>
</dependency>

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
 public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
     User user = new User();
     Map<String, Object> map = new HashMap();
     map.put("id", 1L);
     map.put("name", "三省同学");
     //map转java对象
     BeanUtils.populate(user, map);
     System.out.println(user.toString());
//java转map
     BeanMap testMap = new BeanMap(user);
     System.out.println(testMap);
     System.out.println(testMap.get("id"));
 }

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

输出:

User{id=1, name='三省同学', age=null}
BeanMap<User{id=1, name='三省同学', age=null}>
1

 
 
  • 1
  • 2
  • 3

3、reflect反射工具

反射是一种自然现象,亦是一种光学现象。指光在传播到不同物质时,在分界面上改变传播方向又返回原来物质中的现象。

Reflection(反射) 是 Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查。被private封装的资源只能类内部访问,外部是不行的,但反射能直接操作类私有属性。反射可以在运行时获取一个类的所有信息,(包括成员变量,成员方法,构造器等),并且可以操纵类的字段、方法、构造器等部分。

什么是JAVA反射

代码:

public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    Map<String, Object> map = new HashMap();
    map.put("id", 1L);
    map.put("name", "三省同学");
//map对象转java
    Class<User> userClass = User.class;
    Object object = userClass.newInstance();
    Field[] fields = userClass.getDeclaredFields();
    for (Field field : fields) {
        int mod = field.getModifiers();
        if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) {
            continue;
        }
        field.setAccessible(true);
        field.set(object, map.get(field.getName()));
    }
    System.out.println(object);
 //java对象转map
    Map<String, Object> map1 = new HashMap();
    Field[] declaredFields = object.getClass().getDeclaredFields();
    for (Field field : declaredFields) {
        field.setAccessible(true);
        map1.put(field.getName(), field.get(object));
    }
    System.out.println(map1);
}

 
 
  • 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

结果:

User{id=1, name='三省同学', age=null}
{name=三省同学, id=1, age=null}

 
 
  • 1
  • 2

4、Json工具(推荐)

fastjson 是阿里巴巴开发的一个开源的 JSON 库,它有极快的性能,支持 json 与Collection,Map,javaBean 之间的转换,并且零依赖。

Json相关阅读
代码:

<!-- JSON 解析器和生成器 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
public static void main(String[] args){
    Map<String, Object> map = new HashMap();
    map.put("id", 1L);
    map.put("name", "三省同学");
    //map转java对象
    System.out.println(JSONObject.parseObject(JSONObject.toJSONString(map), User.class));
    // Map<String, Object> s = JSON.parseObject(JSON.toJSONString(user), new TypeReference<Map<String, Object>>() {});
    User user = new User();
    user.setId(1L);
    user.setName("三省同学2");
    //java对象转map
    System.out.println(JSONObject.parseObject(JSONObject.toJSONString(user)));
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

结果:

User{id=1, name='三省同学', age=null}
{"name":"三省同学2","id":1}

 
 
  • 1
  • 2

5、net.sf.cglib.beans.BeanMap工具

代码:

 <dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib</artifactId>
     <version>2.2.2</version>
 </dependency>

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    Map<String, Object> map = new HashMap();
    map.put("id", 1L);
    map.put("name", "三省同学");
    //map转java对象
    Class<User> userClass = User.class;
    Object object = userClass.newInstance();
    BeanMap beanMap = BeanMap.create(object);
    beanMap.putAll(map);
    System.out.println(object);
User user = new User();
    user.setId(2L);
    user.setName("三省同学2");
    //java对象转map
    Map<String, Object> map1 = new HashMap();
    BeanMap beanMap1 = BeanMap.create(user);
    for (Object key : beanMap1.keySet()) {
        map1.put(key + "", beanMap1.get(key));
    }
    System.out.println(map1);
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

结果:

User{id=1, name='三省同学', age=null}
{name=三省同学2, id=2, age=null}

 
 
  • 1
  • 2

6、Introspector工具

代码:

public static void main(String[] args) throws InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException {
    Map<String, Object> map = new HashMap();
    map.put("id", 1L);
    map.put("name", "三省同学");
    //map转java对象
    Class<User> userClass = User.class;
    Object obj = userClass.newInstance();
    BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor property : propertyDescriptors) {
        Method setter = property.getWriteMethod();
        if (setter != null) {
            setter.invoke(obj, map.get(property.getName()));
        }
    }
    System.out.println(obj);
User user = new User();
    user.setId(2L);
    user.setName("三省同学2");
    //java对象转map
    Map<String, Object> map1 = new HashMap();
    BeanInfo beanInfo1 = Introspector.getBeanInfo(user.getClass());
    PropertyDescriptor[] propertyDescriptors1 = beanInfo1
            .getPropertyDescriptors();
    for (PropertyDescriptor property : propertyDescriptors1) {
        String key = property.getName();
        if (key.compareToIgnoreCase("class") == 0) {
            continue;
        }
        Method getter = property.getReadMethod();
        Object value = getter != null ? getter.invoke(user) : null;
        map1.put(key, value);
    }
    System.out.println(map1);
}

 
 
  • 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
  • 32
  • 33
  • 34
  • 35
  • 36

结果:

User{id=1, name='三省同学', age=null}
{name=三省同学2, id=2, age=null}

 
 
  • 1
  • 2
  • 18
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wy971744839

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值