iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >Java对象与Map转换,你了解几种?
  • 126
分享到

Java对象与Map转换,你了解几种?

javaservletjvm 2023-09-13 09:09:42 126人浏览 独家记忆
摘要

前言 开发小伙伴们通常会需要使用到对象和Map互相转换的开发场景,本文主要介绍6种方式,欲知详情,请问下文分解。 实体类: @Dataclass User { Long id; St

前言

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

实体类:

@Dataclass User {    Long id;    String name;    Integer age;}@Overridepublic String toString() {    return "User{" +            "id=" + id +            ", name='" + name + '\'' +            ", age=" + age +            '}';}

1、hutool工具

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

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

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

<dependency><groupId>cn.hutoolgroupId><artifactId>hutool-allartifactId><version>5.8.5version>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}

2、commons.beanutils工具

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

代码:

<dependency>    <groupId>commons-beanutilsgroupId>    <artifactId>commons-beanutilsartifactId>  <version>1.9.1version>dependency>
 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")); }

输出:

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

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);}

结果:

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

4、JSON工具(推荐)

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

Json相关阅读
代码:

<dependency>    <groupId>com.alibabagroupId>    <artifactId>fastjsonartifactId>    <version>1.2.79version>dependency>
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 s = JSON.parseObject(JSON.toJSONString(user), new TypeReference>() {});        User user = new User();    user.setId(1L);    user.setName("三省同学2");    //java对象转map    System.out.println(JSONObject.parseObject(JSONObject.toJSONString(user)));}

结果:

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

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

代码:

 <dependency>     <groupId>cglibgroupId>     <artifactId>cglibartifactId>     <version>2.2.2version> dependency>
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);}

结果:

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

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);}

结果:

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

在这里插入图片描述

点赞 收藏 关注
六十年来狼藉,东壁打到西壁。
如今收拾归来,依旧水连天碧。

来源地址:https://blog.csdn.net/qq_35764295/article/details/127051294

--结束END--

本文标题: Java对象与Map转换,你了解几种?

本文链接: https://www.lsjlt.com/news/405656.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作