一、场景说明

        1、web项目中,需要将返回的null转为空串

        2、有一些工具,没精力去找,索性自行实现一下

        3、用java来实现

        4、支持:实体bean,List<Bean>

        5、其他类型未实现,比如:Map

二、直接上代码

1)核心代码,copy就用
/**
* 实体,属性,String类型,null转空串
* @param obj
*/
public static void nullToEmpty(Object obj) {
if (null == obj) {
return;
}
try {
nullToEmptyEntity(obj);
} catch (Exception e) {
System.out.println("---------");
}
}

/**
*
* @param objList list
* @throws Exception
*/
static void nullToEmptyWithList(List objList) throws Exception{
for (Object obj : objList) {
nullToEmpty(obj);
}
}

/**
*
* @param obj 实体
* @throws Exception
*/
static void nullToEmptyEntity(Object obj) throws Exception {
if (Object.class == obj.getClass()) {
// 无需处理
return;
}
Class clazz = obj.getClass();
Field[] fs = clazz.getDeclaredFields();
// 属性值
Object val = null;
for (Field f : fs) {
boolean isStatic = Modifier.isStatic(f.getModifiers());
if (isStatic) {
// 静态常量,忽视
continue;
}
f.setAccessible(true);
val = f.get(obj);

if (f.getType().equals(String.class)) {
// String类型
if (StrUtil.isEmpty(StringUtils.val(val))) {
f.set(obj, Constants.EMPTY);
}
continue;
}

if (isList(val)) {
// 属性类型为List
nullToEmptyWithList((List)val);
continue;
}
}
}

/**
* 是否是list类型
* @param obj
* @return true: 是
*/
static boolean isList(Object obj) {
if (List.class == obj.getClass()) {
return true;
}
if(ArrayList.class == obj.getClass()) {
return true;
}
if (LinkedList.class == obj.getClass()) {
return true;
}
return false;
}
2)依赖StringUtils.val()方法
/**
* 空串
*/
private static final String EMPTY_STR = "";
/**
* 获取值
* @param obj 请求对象
* @return
*/
public static String val(Object obj) {
if (null == obj) {
return EMPTY_STR;
} else {
String str = obj.toString().trim();
return (isEmpty(str) ? EMPTY_STR : str);
}
}

public static String val(Object obj, int maxLength) {
if (null == obj) {
return EMPTY_STR;
} else {
String str = obj.toString().trim();
if (str.length() > maxLength) {
return str.substring(0, maxLength);
}
return (isEmpty(str) ? EMPTY_STR : str);
}
}