1、web项目中,需要将返回的null转为空串
2、有一些工具,没精力去找,索性自行实现一下
3、用java来实现
4、支持:实体bean,List
5、其他类型未实现,比如:Map
二、直接上代码1)核心代码,copy就用
public static void nullToEmpty(Object obj) { if (null == obj) { return; } try { nullToEmptyEntity(obj); } catch (Exception e) { System.out.println("---------"); } } static void nullToEmptyWithList(List objList) throws Exception{ for (Object obj : objList) { nullToEmpty(obj); } } 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; } } } 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 = ""; 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); } }



