/**
* 将返回值的数据null 转为0
* @param o
* @param <T>
* @return
*/
public static <T> T reflect(T o) {
if (o != null) {
Class<? extends Object> cls = o.getClass();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
f.setAccessible(true);
try {
if (f.getType() == Double.class && f.get(o) == null) {
f.set(o, 0.0);
}
if (f.getType() == Integer.class && f.get(o) == null) {
f.set(o, 0);
}
if (f.getType() == BigDecimal.class && f.get(o) == null){
f.set(o, new BigDecimal(0));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return o;
}
将一个返回值null 转为0 (利用反射)
最新推荐文章于 2023-11-07 23:23:11 发布
本文介绍了一种使用Java反射机制来遍历对象的所有字段,并将其中的null值替换为0或相应数值类型的默认值的方法。这种方法适用于包含Double、Integer及BigDecimal类型字段的对象。
1377

被折叠的 条评论
为什么被折叠?



