Tool method: Convert all null fields in the object to empty strings at one time

When our Java object is responding to the front end, or doing data export, we don't want to return the null property value in the object directly to the front end, otherwise the display or export is a null, which is not very user-friendly.

 

If we process the fields one by one, this will not only increase the manpower, but also make the logic in the code redundant, which is not elegant.

So I wrote a general method below: a method to convert the null value of the String type property in the object to an empty string. The specific code is as follows:

/**
 * 把对象中的 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;
}

Here is the effect:

【Before method processing】

Before the method is called, the unset field value in user is null

 [After method processing]

As you can see, after we call the above method, the null field disappears and becomes an empty string.

Guess you like

Origin blog.csdn.net/sunnyzyq/article/details/120948619