zoukankan      html  css  js  c++  java
  • java反射判断对象空字段

    public class ReflectionUtils {
    
        private final static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
    
        /**
         * 检查字段
         */
        public static class CheckFiled{
            /**
             * 检查字段是否为null 或者 ""
             * @param source 需要校验的实体
             * @param excludeFields 不需要校验的属性集合
             * @return
             */
            public static void checkFileNullAble(Object source, String ... excludeFields){
    
                List<String> excludeFieldsList = new ArrayList<>();
                if (excludeFields.length > 0) {
                    excludeFieldsList = Arrays.asList(excludeFields);
                }
    
                try {
                    // 取到obj的class, 并取到所有属性
                    Field[] fs = source.getClass().getDeclaredFields();
                    // 遍历所有属性
                    for (Field f : fs) {
                        isNullField(f,source,excludeFieldsList);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
            }
    
            private static void isNullField(Field f,Object source,List<String> excludeFieldsList) throws Exception {
                // 设置私有属性也是可以访问的
                f.setAccessible(true);
    
                //没有需要排除的属性
                if (excludeFieldsList == null || excludeFieldsList.size() == 0) {
                    Object filedValue = f.get(source);
                    if (filedValue== null || "".equals(filedValue.toString())){
                        throw new Exception("Parameter "+f.getName()+"  is null or empty!");
                    }
                    return;
                }
    
                if(!excludeFieldsList.contains(f.getName())) {
                    if ((f.get(source) == null || "".equals(f.get(source).toString()))){
                        throw new Exception("Parameter "+f.getName()+"  is null or empty!");
                    }
                }
            }
    
        }
    
    }
  • 相关阅读:
    数学符号表
    对比深度学习十大框架:TensorFlow最流行但并不是最好
    支持向量机通俗导论(理解SVM的三层境界)
    Annotation
    Struts2的拦截器
    DLL文件的引用
    JS引擎
    Windows窗口的创建
    解决构造器多参数的设计问题
    静态工厂对比构造器之优缺点
  • 原文地址:https://www.cnblogs.com/zfzf1/p/11320503.html
Copyright © 2011-2022 走看看