Java 用反射实现实体类属性 not null 校验

2020-04-16  本文已影响0人  夹胡碰

自定义注解实属性 not null 校验, 代码如下

// 标记非null字段
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface VerifyNotNull {
}
// 非null校验工具类
public final class VerifyUtil {

    private VerifyUtil(){
        throw new AssertionError("No " + VerifyUtil.class.getName() + " instances for you !");
    }
    //校验方法
    public static void Verify(Object o){
        Class<?> oClass = o.getClass();
        Field[] fields = oClass.getDeclaredFields();
        for(Field field : fields){
            field.setAccessible(true);
            // must not be null
            if(field.isAnnotationPresent(VerifyNotNull.class)){
                try {
                    Assert.notNull(field.get(o), field.getName() + " must not be null !");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class User {
    
    private Integer id;

    @VerifyNotNull
    private String name;
}
User user = new User();
VerifyUtil.Verify(user);
// 校验报错
Exception in thread "main" java.lang.IllegalArgumentException: name must not be null !
    at org.springframework.util.Assert.notNull(Assert.java:134)
    at com.jiafupeng.controller.util.VerifyUtil.Verify(VerifyUtil.java:27)
    at com.jiafupeng.controller.util.VerifyUtil.main(VerifyUtil.java:37)
上一篇 下一篇

猜你喜欢

热点阅读