当前位置:网站首页>使用工具类把对象中的null值转换为空字符串(集合也可以使用)
使用工具类把对象中的null值转换为空字符串(集合也可以使用)
2022-08-05 09:35:00 【BOBO阿】
把单个对象中的String类型的null字段,转换为空字符串
/** * 把单个对象中的String类型的null字段,转换为空字符串 * 注意:只能转换String类型的字段 * @param <T> 待转化对象类型 * @param cls 待转化对象 * @return 转化好的对象 */
public static <T> T nullToString(T cls) {
Field[] fields = cls.getClass().getDeclaredFields();
if (fields == null || fields.length == 0) {
return cls;
}
for (Field field : fields) {
if ("String".equals(field.getType().getSimpleName())) {
field.setAccessible(true);
try {
Object value = field.get(cls);
if (value == null) {
field.set(cls, "");
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
return cls;
}
把集合中的所有对象中的String类型的null字段,转换为空字符串
/** * 把集合中的所有对象中的String类型的null字段,转换为空字符串 * 注意:只能转换String类型的字段 * @param sourceList 待转化的集合 * @return 转化好的集合 */
public static <T> List<T> listNullToString(List<T> sourceList) {
ArrayList<T> resultList = new ArrayList<>();
for (T cls : sourceList) {
Field[] fields = cls.getClass().getDeclaredFields();
if (fields == null || fields.length == 0) {
resultList.add(cls);
}
for (Field field : fields) {
if ("String".equals(field.getType().getSimpleName())) {
field.setAccessible(true);
try {
Object value = field.get(cls);
if (value == null) {
field.set(cls, "");
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
resultList.add(cls);
}
return resultList;
}
边栏推荐
- Example of Noise Calculation for Amplifier OPA855
- 无题二
- PAT乙级-B1019 数字黑洞(20)
- 【LeetCode】623. Add a row to the binary tree
- 放大器OPA855的噪声计算实例
- 什么是CRM决策分析管理?
- Excuse me, guys, is it impossible to synchronize two databases in real time using Flink SQL CDC?
- 2022-08-01 回顾基础二叉树以及操作
- 欧盟 | 地平线 2020 ENSEMBLE:D2.13 SOTIF Safety Concept(上)
- Advanced usage of C language
猜你喜欢

ECCV 2022 Oral Video Instance Segmentation New SOTA: SeqFormer & IDOL and CVPR 2022 Video Instance Segmentation Competition Champion Scheme...

pytorch余弦退火学习率CosineAnnealingLR的使用

科普大佬说 | 港大黄凯斌老师带你解锁黑客帝国与6G的关系

What is CRM Decision Analysis Management?

Oracle临时表空间作用

微服务 技术栈

Creo 9.0 基准特征:基准轴

mysql进阶(二十七)数据库索引原理

2.4G无线收发模块的应用

【ASM】字节码操作 方法的初始化 Frame
随机推荐
阿里云存储的数据库是怎么自动加快加载速度的呢www.cxsdkt.cn怎么设置案例?
21 Days of Deep Learning - Convolutional Neural Networks (CNN): Clothing Image Classification (Day 3)
leetcode points to Offer 10- I. Fibonacci sequence
Redis源码解析:Redis Cluster
Wei Dongshan Digital Photo Frame Project Learning (6) Transplantation of tslib
2022.8.3
leetcode refers to Offer 10- II. Frog jumping steps
七夕浪漫约会不加班,RPA机器人帮你搞定工作
leetcode: 529. 扫雷游戏
无题十
Seata source code analysis: initialization process of TM RM client
PAT乙级-B1020 月饼(25)
如何实现按键的短按、长按检测?
欧盟 | 地平线 2020 ENSEMBLE:D2.13 SOTIF Safety Concept(下)
正则表达式replaceAll()方法具有什么功能呢?
MQTT X Newsletter 2022-07 | 自动更新、MQTT X CLI 支持 MQTT 5.0、新增 conn 命令…
仿SBUS与串口数据固定转换
【ASM】字节码操作 方法的初始化 Frame
dotnet OpenXML parsing PPT charts Getting started with area charts
Example of Noise Calculation for Amplifier OPA855