使用java反射进行对象中属性空值校验

关键词:java注解、反射

直接贴代码:

注解类如下:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})//次注解作用于类和字段上
public @interface MyNotNull {
}

工具类如下:

public class StringUtil {

    /**
     * 根据对象上的注解来判断属性是不是为空
     *
     * @author 
     * @date 2019/2/15 17:27
     */
    public static boolean isEmptyAnnotation(Object object) throws Exception {
        if (object != null) {
            // 拿到该类
            Class<?> clz = object.getClass();
            // 获取实体类的所有属性,返回Field数组
            Field[] fields = clz.getDeclaredFields();
            for (Field field : fields) {
                /*获取私有的*/
                field.setAccessible(true);
                /*判断是不是使用MyNotNull注解*/
                if (field.getDeclaredAnnotation(MyNotNull.class) == null) {
                    break;
                }
                /*如果为空返回true*/
                /*StringUtils工具类为org.apache.commons.lang所属*/
                if (field.get(object) == null || StringUtils.isEmpty(field.get(object).toString())) {
                    return true;
                }
            }
        }
        return false;
    }

   /**
     * 判断是否为空
     * null或空字符串
     * 是:true
     * 否:false
     *
     * @author 
     * @date 2019/2/15
     */
    public static boolean isEmpty(String... strArray) {
        for (String str : strArray) {
            if (StringUtils.isEmpty(str)) {
                return true;
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/lwcyd/article/details/88013552