博客
关于我
map和bean的相互转换
阅读量:797 次
发布时间:2023-02-07

本文共 2083 字,大约阅读时间需要 6 分钟。

Bean与Map转换工具类详解

1. 概述

本文将详细介绍两个核心功能:Bean转Map与Map转Bean。通过代码示例和对注解的解读,阐述实现原理与应用场景。

2. Bean转Map

2.1 方法说明

public static Map
bean2Map(T source) throws IllegalAccessException { Map
result = new HashMap<>(); Class
sourceClass = source.getClass(); Field[] sourceFields = sourceClass.getDeclaredFields(); for (Field field : sourceFields) { field.setAccessible(true); FieldName fieldNameAnnotation = field.getAnnotation(FieldName.class); if (fieldNameAnnotation == null) { result.put(field.getName(), field.get(source)); } else { if (!fieldNameAnnotation.Ignore()) { String headerName = fieldNameAnnotation.value(); result.put(headerName, field.get(source)); } } } return result;}

2.2 注解解读

@FieldName注解用于自定义字段名,支持忽略某些字段。字段名默认为空,忽略标志默认为false

3. Map转Bean

3.1 方法说明

public static T map2Bean(Map
source, Class
instance) { try { T object = instance.newInstance(); Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); FieldName fieldNameAnnotation = field.getAnnotation(FieldName.class); if (fieldNameAnnotation != null) { String headerName = fieldNameAnnotation.value(); Object value = source.get(headerName); field.set(object, value); } else { String fieldName = field.getName(); Object value = source.get(fieldName); field.set(object, value); } } return object; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null;}

3.2 注解解读

同样,@FieldName用于自定义字段名,支持忽略某些字段。字段名默认为空,忽略标志默认为false

4. 注意事项

  • 注解字段名优先于字段名本身,若注解未标注,默认使用字段名。
  • 忽略标志控制字段是否参与转换。
  • 方法均需处理访问权限,通过setAccessible(true)确保可访问。

5. 应用场景

  • 数据持久化转换:将JavaBean序列化为JSON、XML等数据格式。
  • API请求参数转换:将参数Map反转为JavaBean实例。
  • 数据交互工具:实现跨平台数据转换与传输。

转载地址:http://ogufk.baihongyu.com/

你可能感兴趣的文章
Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
查看>>
Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
查看>>
Objective-C实现Collatz 序列算法(附完整源码)
查看>>
Objective-C实现comb sort梳状排序算法(附完整源码)
查看>>
Objective-C实现combinationSum组合和算法(附完整源码)
查看>>
Objective-C实现combinations排列组合算法(附完整源码)
查看>>
Objective-C实现combine With Repetitions结合重复算法(附完整源码)
查看>>
Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
查看>>
Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
查看>>
Objective-C实现connected components连通分量算法(附完整源码)
查看>>
Objective-C实现Connected Components连通分量算法(附完整源码)
查看>>
Objective-C实现Convex hull凸包问题算法(附完整源码)
查看>>
Objective-C实现convolution neural network卷积神经网络算法(附完整源码)
查看>>
Objective-C实现convolve卷积算法(附完整源码)
查看>>
Objective-C实现coulombs law库仑定律算法(附完整源码)
查看>>
Objective-C实现counting sort计数排序算法(附完整源码)
查看>>
Objective-C实现countSetBits设置位的数量算法(附完整源码)
查看>>
Objective-C实现currency converter货币换算算法(附完整源码)
查看>>
Objective-C实现cycle sort循环排序算法(附完整源码)
查看>>
Objective-C实现data transformations数据转换算法(附完整源码)
查看>>