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!");
                    }
                }
            }
    
        }
    
    }
  • 相关阅读:
    KVM安装之脚本和镜像目录树准备
    KVM安装之网桥
    安装KVM虚拟机步骤
    NFS搭建配置
    为项目组搭建开发测试环境介绍
    VMWare虚拟机copy后网卡不是eth0解决办法
    安装Oracle 10g和SQLServer2008(仅作学习使用VirtualBox虚拟机来安装节省电脑资源)
    常用的SQL语句
    在web项目中集成Spring
    IOC容器装配Bean(注解方式)
  • 原文地址:https://www.cnblogs.com/zfzf1/p/11320503.html
Copyright © 2011-2022 走看看