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!");
                    }
                }
            }
    
        }
    
    }
  • 相关阅读:
    while...break 实例
    java ++ -- 异或 短路与 短路或 三目条件
    Java StringBuffer与StringBuider
    输入任意5个整数,输出它们的和。
    java输入年份和月份,输出天数
    进制转换
    luogu 4884 多少个1?
    SDOI2013 随机数生成器
    CQOI2018 破解D-H协议
    模板BSGS(SDOI2011计算器) 模板EXBSGS
  • 原文地址:https://www.cnblogs.com/zfzf1/p/11320503.html
Copyright © 2011-2022 走看看