栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java】反射 | web请求返回值null转空串

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java】反射 | web请求返回值null转空串

一、场景说明

        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);
        }
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926740.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号