Java注解之运行时注解

曾经终败给现在 2022-05-09 11:46 330阅读 0赞

注解的生命周期

  • RetentionPolicy.SOURCE 注解只在源代码中,编译成class文件之后,就没了
  • RetentionPolicy.CLASS 注解在java文件编译成class文件之后,依然存在,但是运行起来就没有了
  • RetentionPolicy.RUNTIME 注解在运行起来之后依然存在,程序可以通过类反射获取这些信息

RetentionPolicy.RUNTIME

这里我们介绍运行时注解

  1. 首先建立一个自定义注解

    @Retention(RetentionPolicy.RUNTIME)
    public @Interface FaceDemo{

    1. String value() default "";

    }

  2. 使用自定义注解

    public class FaceTest {

    1. @FaceDemo
    2. public String str ="";

    }

  3. 创建一个解析器

    public class FaceDemoProcessor {

    1. public static void main(String[] args){
    2. Class<?> cls = FaceTest.class;
    3. try{
    4. Field str = cls.getField("str");//获取指定成员属性
    5. boolean b = str.isAnnotationPresent(FaceDemo.class);//这个属性上是否有这个注解
    6. if(b){
    7. //获取所有的注解
    8. Annotation[] annotations = str.getAnnotations();
    9. System.out.println(annotations.length);
    10. //获取指定注解
    11. FaceDemo annotation = str.getAnnotation(FaceDemo.class);
    12. System.out.println(annotation.value());
    13. }
    14. } catch (NoSuchFieldException e) {
    15. e.printStackTrace();
    16. }
    17. }

    }

  4. 输出

    1
    自定义运行时注解

  5. 通过类反射获取注解的几个常用方法

    /**

    /**

    • 获取所有注解
      */
      public Annotation[] getAnnotations();

    /**

    • 获取所有注解,忽略继承的注解
      */
      public Annotation[] getDeclaredAnnotations();

    /**

    • 指定注解是否存在该元素上,如果有则返回true,否则false
      */
      public boolean isAnnotationPresent(Class<? extends Annotation> annotationType);

    /**

    • 获取Method中参数的所有注解
      */
      public Annotation[][] getParameterAnnotations();

发表评论

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

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

相关阅读