当前位置:网站首页>使用工具类把对象中的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;
}
边栏推荐
猜你喜欢
随机推荐
ECCV 2022 Oral Video Instance Segmentation New SOTA: SeqFormer & IDOL and CVPR 2022 Video Instance Segmentation Competition Champion Scheme...
PAT乙级-B1020 月饼(25)
2022.8.3
【LeetCode】623. Add a row to the binary tree
蚁剑webshell动态加密连接分析与实践
CPU的亲缘性affinity
Overall design and implementation of Kubernetes-based microservice project
Can MySQL use aggregate functions without GROUP BY?
我的杂记链接
5.部署web项目到云服务器
Oracle temporary table space role
sql server中 两表查询 平均数 分组
【零基础玩转BLDC系列】无刷直流电机无位置传感器三段式启动法详细介绍及代码分享
Creo 9.0 基准特征:基准轴
PAT Class B-B1019 Digital Black Hole (20)
HStreamDB Newsletter 2022-07|分区模型优化、数据集成框架进一步完善
The Seven Weapons of Programmers
无题七
深度学习21天——卷积神经网络(CNN):天气识别(第5天)
为什么我推荐使用智能化async?









