注解的基本知识

1、什么是注解

  • Annotation是从JDK5.0开始引进的新技术
  • Annotation的作用
    • 不是程序本身,可以对程序作出解释(这一点与注释(Comment)没什么区别)
    • 可以被其他程序(比如:编译器等)读取
  • Annotation
    • 注解是以"@注解名"在代码中存在的,还可以添加一些参数值,例如:@SuppressWarnings(value="unchecked").
  • Annotation在哪里使用
    • 可以附加在package,class,method,field等上面,相当于给她们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问。

2、内置注解(系统已存在的注解)

  • @Override:定义在java.lang.Override中,此注解只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明。
  • @Deprecate:定义在java.lang.Deprecate中,此注解可以用于修饰方法,属性,类,表示不鼓励程序猿使用这样的元素,通常是因为它很危险或者存在更好的选择。
  • @SuppressWarnings:定义在java.lang.SuppressWarnings中,用与抑制编译时的警告信息。
    • 与前面两个注释有所不同,你需要添加一个参数才能正确使用,这些参数都是已经定义好了的,我们选择性的使用就好了
      • @SuppressWarning("all")
      • @SuppressWarning("unchecked")
      • @SuppressWarning(value={"unchecked", "deprecation"})
      • 等等.......
 

3、元注解

  • 元注解的作用就是负责注解其他注解,java定义了四个标准的meta-annotation类型,他们被提供对其他annotation类型作说明,
  • 这些类型和它们所支持的类在java.lang.annotation包中可以找到(@Target, @Retention, @Documented, @Inherited )
    • @Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
    • @Retention:表示需要什么级别保存该注解信息,用于描述注解的生命周期
      • SOURCE<CLASS<RUNTIME
    • Document:说明该注解将被包含在javadoc中
    • Inherited:说明子类可以继承父类中的该注解

4、自定义注解

  • 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
  • 分析:
    • @interface用来声明一个注解,格式:public@interface注解名{定义内容}
    • 其中的每一个方法实际上是声明了一个配置参数
    • 方法的名称就是参数的名称
    • 返回值类型就是参数的类型(返回值只能是基本类型,Class,String,enum)
    • 可以通过default来声明参数的默认值
    • 如果只有一个参数成员,一般参数名为value,在使用时就可以省略参数名称
    • 注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值

以Deprecated注解为例:

 1 @Documented
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
 4 public @interface Deprecated {
 5     /**
 6      * Returns the version in which the annotated element became deprecated.
 7      * The version string is in the same format and namespace as the value of
 8      * the {@code @since} javadoc tag. The default value is the empty
 9      * string.
10      *
11      * @return the version string
12      * @since 9
13      */
14     String since() default "";
15 
16     /**
17      * Indicates whether the annotated element is subject to removal in a
18      * future version. The default value is {@code false}.
19      *
20      * @return whether the element is subject to removal
21      * @since 9
22      */
23     boolean forRemoval() default false;
24 }
Deprecated
 
原文地址:https://www.cnblogs.com/zitai/p/12234217.html