搜索中心对象中null属性字段赋值为空字符串

This commit is contained in:
CD
2023-01-04 10:14:36 +08:00
parent 1c6a24b7e9
commit a8ebce11c3
2 changed files with 55 additions and 5 deletions
@@ -0,0 +1,34 @@
package com.adc.da.utils.util;
import java.lang.reflect.Field;
public class NullToEmptyUtil {
/**
* 把对象中的 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;
}
}