Use java reflection mechanism to realize interface parameter verification [reflection mechanism () 1)]

Using java reflection mechanism to realize interface parameter verification

Business scene :

      There are many interfaces for adding or modifying operations that need to record information such as the id and name of the operator. Therefore, the operator information needs to be verified before the interface executes the business code. Because the objects passed in are different, but they all have operator information, so the method of dynamically obtaining object information is used to verify parameters (reflection).
      In order to save a lot of verification and duplication code, reflection is used here.
      [The specific code is as follows]:

public static void checkOperator(Object operator) throws Exception {
    
    
        try{
    
    
            //需要检查属性数组
            String dataNames[] = {
    
    "operatorId","operatorName"};
            Class operatorObj = operator.getClass(); //实际对象
            Field dataField = null;                  //属性
            Object obj = null;                       //属性值
            for(String dataName : dataNames){
    
    
                dataField = operatorObj.getDeclaredField(dataName); //根据属性名获取属性
                dataField.setAccessible(true);          //开启属性访问
                obj = dataField.get(operator);          //获取属性值
                if(ObjectUtils.isEmpty(obj))            //空判
                    throw new Exception();
            }
        }catch (NoSuchFieldException | IllegalAccessException e){
    
    
            throw new NoSuchFieldException("此对象不存在操作人信息!");
        } catch (Exception e){
    
    
            throw new Exception("操作人信息为空!");
        }
    }

Reflection consumes more system resources, so it needs to be used with caution! (Here is only a reference example for the simple use of reflection)

Guess you like

Origin blog.csdn.net/AKALXH/article/details/116520769