• Java Annotation


    https://blog.csdn.net/briblue/article/details/73824058

    Annotation就是给代码打的标签,

    元Annotation,定义Annotation本身的一些属性,常用的以下几种,

    Retention注解

    Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
    1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
    2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
    3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.

    Documented 注解

    Documented 注解表明这个注解应该被 javadoc工具记录. 

    Target注解

    @Target说明了Annotation所修饰的对象范围:

    1.CONSTRUCTOR:用于描述构造器
    2.FIELD:用于描述域
    3.LOCAL_VARIABLE:用于描述局部变量
    4.METHOD:用于描述方法
    5.PACKAGE:用于描述包
    6.PARAMETER:用于描述参数
    7.TYPE:用于描述类、接口(包括注解类型) 或enum声明

    为什么要有注解?

    注解是介于代码和注释之间的存在,

    用于将代码中的对象,进行分类或标识,这样在编译或运行时,可以做对不同的分类做不同的处理

    如何使用?

    注解通过 @interface关键字进行定义

    public @interface TestAnnotation { }

    注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {
      public int id() default -1;
      public String msg() default "Hi";

    }

    使用的时候,

    @TestAnnotation(id=3,msg="hello annotation") public class Test { }

    或者,用默认值

    @TestAnnotation() public class Test { }

    如果是runtime的Annotation,

    可以在代码里面这样获取,

    boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);

    if ( hasAnnotation ) {
      TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);

    System.out.println("id:"+testAnnotation.id());
    System.out.println("msg:"+testAnnotation.msg());

    常用注释

    @SuppressWarnings,抑制告警

    @SuppressWarnings("unchecked"),强制类型转换时的告警

    @SuppressWarnings("deprecation")

  • 相关阅读:
    单词统计
    易学app开发——10
    易学app开发--9
    易学app开发——8
    易学app开发----7
    易学app开发----6
    易学app开发----5
    易学app开发----4
    易学app开发----3
    顶会热词统计
  • 原文地址:https://www.cnblogs.com/fxjwind/p/11726236.html
Copyright © 2020-2023  润新知