Java自定义注解实现验证实体类属性的合法性

女爷i 2022-01-27 08:19 411阅读 0赞

一、注解的基础

1.注解的定义:Java文件叫做Annotation,用@interface表示。

2.元注解:@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。

3.注解的保留策略:

@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含

@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

4.注解的作用目标:

@Target(ElementType.TYPE) // 接口、类、枚举、注解

@Target(ElementType.FIELD) // 字段、枚举的常量

@Target(ElementType.METHOD) // 方法

@Target(ElementType.PARAMETER) // 方法参数

@Target(ElementType.CONSTRUCTOR) // 构造函数

@Target(ElementType.LOCAL_VARIABLE) // 局部变量

@Target(ElementType.ANNOTATION_TYPE) // 注解

@Target(ElementType.PACKAGE) // 包

5.注解包含在javadoc中:

@Documented

6.注解可以被继承:

@Inherited

1、自定义注解类:

  1. import java.lang.annotation.Documented;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Inherited;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7. /**
  8. * 请求参数校验
  9. * @author Xuan
  10. *
  11. */
  12. //注解包含于Javadoc中
  13. @Documented
  14. //注解的作用目标
  15. @Target(ElementType.FIELD)
  16. //注解可以被继承
  17. @Inherited
  18. //注解的保留策略
  19. @Retention(RetentionPolicy.RUNTIME)
  20. public @interface NotNull {
  21. /**
  22. * 必须参数
  23. * @return
  24. */
  25. boolean flag() default true;
  26. }

2、实体类(规则需生成getandset方法):

  1. import AnnotationResolve;
  2. public class Pojo extends AnnotationResolve{
  3. @NotNull
  4. private String name;
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. }

3、自定义注解解析器:

  1. import java.lang.reflect.Field;
  2. import java.lang.reflect.Method;
  3. /**
  4. * 自定义注解解析器
  5. * @author Xuan
  6. *
  7. */
  8. public class AnnotationResolve {
  9. public boolean validate() throws NoSuchMethodException, SecurityException,Exception {
  10. // 获取类的属性
  11. Field[] fields = this.getClass().getDeclaredFields();
  12. for (Field field : fields) {
  13. System.out.println("1");
  14. if (field.isAnnotationPresent(NotNull.class)) {
  15. NotNull notnull = field
  16. .getAnnotation(NotNull.class);
  17. if (notnull.flag()) {
  18. // 如果类型是String
  19. // 如果type是类类型,则前面包含"class ",后面跟类名
  20. if (field.getGenericType().toString().equals("class java.lang.String")) {
  21. // 拿到该属性的getet方法
  22. Method m = this.getClass().getMethod("get" + getMethodName(field.getName()));
  23. System.out.println(field.getName());
  24. // 调用getter方法获取属性值
  25. String val = (String) m.invoke(this);
  26. if (val == null || val.equals("")) {
  27. throw new Exception(field.getName() + " 不能为空!");
  28. }
  29. System.out.println("String t2ype:" + val);
  30. } else if (field.getGenericType().toString().equals("class java.lang.Integer")) {
  31. Method m = this.getClass().getMethod("get" + getMethodName(field.getName()));
  32. // 调用getter方法获取属性值
  33. Integer val = (Integer) m.invoke(this);
  34. if (val == null) {
  35. throw new Exception(field.getName() + " 不能为空!");
  36. }
  37. System.out.println("String ty1pe:" + val);
  38. }
  39. }
  40. }
  41. }
  42. return true;
  43. }
  44. /**
  45. * 把一个字符串的第一个字母大写、效率是最高的
  46. */
  47. private String getMethodName(String fildeName) throws Exception {
  48. byte[] items = fildeName.getBytes();
  49. items[0] = (byte) ((char) items[0] - 'a' + 'A');
  50. return new String(items);
  51. }
  52. }

4、测试类:

  1. public class test {
  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. Pojo pojo = new Pojo();
  7. pojo.setName("轩");
  8. try {
  9. boolean flag = pojo.validate();
  10. if(flag){
  11. System.out.println("验证通过");
  12. }else {
  13. System.out.println("验证失败");
  14. }
  15. } catch (NoSuchMethodException e) {
  16. e.printStackTrace();
  17. } catch (SecurityException e) {
  18. e.printStackTrace();
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }

5、如下图:

在这里插入图片描述

6、遇到困难可以评论(有信必回)小轩微信号tangchenxuan1999

发表评论

表情:
评论列表 (有 0 条评论,411人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java实现定义注解

    前言      上一篇文章介绍了注解的一些基本知识,这次来介绍下如何实现自定义注解及注解如何使用。 正文      注解是一种能被添加到java源代码中的元数据,