美文网首页
Java 用反射实现实体类属性 not null 校验

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

作者: 夹胡碰 | 来源:发表于2020-04-16 15:33 被阅读0次

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

  • @VerifyNotNull 非null注解
// 标记非null字段
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface VerifyNotNull {
}
  • VerifyUtil 工具类
// 非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();
                }
            }
        }
    }
}
  • 测试User实体类
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)

相关文章

网友评论

      本文标题:Java 用反射实现实体类属性 not null 校验

      本文链接:https://www.haomeiwen.com/subject/uxorvhtx.html