替换具体对象中的“null“属性值的字段值为null

23 篇文章 0 订阅

在java对象中"null"属性值不太合理,用null来代替会更好

public List<CmsContentDTO> deleteNullData(List<CmsContentDTO> newList){
    //反射获取类
    Class c = CmsContentDTO.class;
    //获取DTO对象的所有定义的属性信息Filed
    Field[] fileds = c.getDeclaredFields();
    for(int i=0;i<newList.size();i++){
        CmsContentDTO cmsContentDTO = newList.get(i);
        for(int j=0;j<fileds.length;j++){
            Field f = fileds[j];
            try {
                //对象中的属性是private的需要设置accessible才可用
                 f.setAccessible(true);
                //遍历每个属性值
                if("null".equals(f.get(cmsContentDTO))){
                    //拼接set方法
                    String methodName = "set" + f.getName().substring(0,1).toUpperCase()+f.getName().substring(1,f.getName().length());
                    //获取方法
                    Method method = c.getDeclaredMethod(methodName, f.getType().getCanonicalName().getClass());
                    //直接给属性赋值null会报空指针
                    String nullName = null;
                    //调用方法
                    method.invoke(cmsContentDTO,nullName);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
    return newList;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值