工具方法:一次性将对象中所有null字段,转为空字符串

当我们的 Java 对象在响应前端,或者在做数据导出的时候,我们并不希望将对象中为 null 的属性值直接返回给前端,不然显示或导出的就是一个 null ,这样对用户不是很友好。

 

如果我们一个个字段的去处理,这样不但增加了人力,而且使得代码中逻辑冗余,显得不够优雅。

于是下面我写了一个通用方法:将对象中的 String 类型属性的 null 值转换为空字符串的方法,具体代码如下:

/**
 * 把对象中的 String 类型的null字段,转换为空字符串
 * 
 * @param <T> 待转化对象类型
 * @param cls 待转化对象
 * @return 转化好的对象
 */
public static <T> T noNullStringAttr(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;
}

下面是效果:

【方法处理前】

在没有调用方法前,user 中未设置的字段值为 null

 【方法处理后】

可以看到,我们调用上面的方法后,null 字段就消失了,变为了空字符串。

猜你喜欢

转载自blog.csdn.net/sunnyzyq/article/details/120948619