在一些场景,例如 mybatis 的数据插入时,对象属性不能为 null。如果对象属性存在 null 的情况,可以先将空值属性置为空字符串。
如何快速实现?在 Java 中,可以使用反射来快速将一个对象的空值属性置为空字符串。下面是示例代码。
package com.test.utils;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
@Slf4j
public class NoNullStringAttr {
/**
* 把对象中的 String 类型的 null字段转换为空字符串
*
* @param cls 待转化对象
* @param <T> 待转化对象类型
* @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) {
log.error("对象空值转化处理异常", e);
}
}
}
return cls;
}
}