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!");
                }
            }
        }

    }

}

 

posted @ 2019-08-08 12:56  zfzf1  阅读(1031)  评论(0编辑  收藏  举报