基于反射机制判断对象指定属性是否为空

1.概述

在最近项目的开发中,在自身的服务中会调用其它的各种服务或资源,因此为了避免资源浪费,降低无效请求,会在入参时进行参数的校验,过滤那些参数异常的请求。然而由于某些对象参数较多,而很多又是业务需要的必填参数,导致接口中充斥着大量的参数判断语句,造成代码冗余。为了改善这种情况,利用java的反射技术,编写了一个对象属性自动过滤工具类。

2.反射过滤工具类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.awifi.video.cloud.common.constant.ErrorContents;
import com.awifi.video.cloud.common.exception.VideoCloudException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
  * @Description: 反射判断对象属性是否为空工具类
  * @Author Marin
  * @Date 2020/9/23 17:22
  */
public class ParamCheck {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParamCheck.class);

    /**
      * @description: 检查所有属性是否为空
      * @param {Object,指定对象}
      * @return {}
      * @author Marin
      * @date 2020/9/23 17:28
      */
    public static void checkAllParamsIsNull(Object obj) {
        try {
            for(Field f : obj.getClass().getDeclaredFields()){
                f.setAccessible(true);
                if(f.get(obj) == null || f.get(obj).equals("")){
                    LOGGER.error(f.getName()+"不能为空");
                    throw new VideoCloudException(ErrorContents.ERROR_NUM_006,f.getName());
                }
            }
        } catch (Exception e) {
            LOGGER.error("参数校验异常:{}",e.getMessage());
        }
    }

    /**
      * @description: 校验指定参数不能为空
      * @param {Object:指定对象,params:指定属性集}
      * @return {}
      * @author Marin
      * @date 2020/9/23 17:29
      */
    public static void checkParamsIgnoreSome(Object obj,String ...params) {

        Field[] declaredFields = obj.getClass().getDeclaredFields();

        List<Field> list1 = Arrays.asList(declaredFields);
        List<Field> arrList = new ArrayList<>(list1);

        //先获取需要校验的属性,存入List
        for(int i=0;i<params.length;i++) {
            for(int j=0;j<declaredFields.length;j++) {
                if(declaredFields[j].getName().equals(params[i])) {
                    arrList.remove(declaredFields[j]);
                    break;
                }
            }
        }

        //校验指定的属性是否为空
        try {
            for (int i=0;i<arrList.size();i++) {
                for(Field f : declaredFields) {
                    if (arrList.get(i).getName().equals(f.getName())) {
                        f.setAccessible(true);
                        if(f.get(obj) == null || f.get(obj).equals("")){
                            LOGGER.error(f.getName()+"不能为空");
                            throw new VideoCloudException(ErrorContents.ERROR_NUM_006,f.getName());
                        }
                        break;
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    /*public static void main(String[] args) {
        BaseResult baseResult = new BaseResult();
        baseResult.setData("hello");
        baseResult.setErrorMsg("error");
        System.out.println("-------------");
        ParamCheck.checkParamsIgnoreSome(baseResult, "subCode", "subMsg");
    }*/
}

3.Field一些属性介绍

方法名称返回值解释
get(Object obj)Object返回这个object对应field字段的Object
getChar(Object obj)/getInteger(Object obj)/…char/integer与上面方法作用类似,只不过返回具体形式值
set(Object obj, Object value)void设置obj对象的调用方法的这个field的值为value
getDeclaringClassClass返回定义中的Class对象
getName()String得到属性名称的字符串
setAccessible(boolean flag)void设置是否能够使用该属性的get、set方法
isAccessible()boolean查看是否能够使用get、set方法
getDeclaredAnnotations()Annotation[]返回该方法上的所有注解

4.小结

1.检查所有属性是否为空的原理:首先利用反射获取该对象的所有属性集,然后依次遍历,获取每个属性对应的object,再判断object是否为空,为空则进行错误打印和抛出异常;
2.检查指定属性是否为空的原理:首先利用反射获取该对象的所有属性集,然后对比输入指定属性,去除原对象中的指定属性,在进行剩余属性是否为空的校验。

5.参考文章

1.https://www.jianshu.com/p/bd864b93b420

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值