Java 注解

  Java 注解(Annotation)是 JDK5.0 引入的一种注释机制。Java 注解可以通过反射获取注解内容。在编译器生成类文件时,注解可以被嵌入到字节码中。Java 虚拟机可以保留注解内容,在运行时可以获取到注解内容

内置注解

@override: 表示重写方法,若父类或引用的接口没有该方法,则编译错误

@Deprecated: 标记过时元素,不建议使用的元素,因为它存在危险或存在更好的选择

@SuppressWarnings: 用于抑制编译时的警告信息

元注解

@Target:用于描述注解的使用范围

@Retention:用于描述注解的生命周期(SOURCE < CLASS < RUNTIME

@Document: 说明该注解是否被包含在 javadoc 中

@Inherited: 说明子类可以继承父类的该注解

自定义注解

定义:

1 @Target({ElementType.TYPE, ElementType.METHOD}) // 应用于类、接口 应用于方法
2 @Retention(RetentionPolicy.RUNTIME) // 运行时有效
3 public @interface Test {
4     String value() default "";
5     String name();
6     int age();
7 }
View Code

使用说明:

有默认值的属性可以不用初始化

其他属性初始化方法 属性名=属性值

当注解只有一个属性且属性名为value时可以省略"value="

元注解参数说明:

 1 public enum ElementType {
 2     /** Class, interface (including annotation type), or enum declaration */
 3     TYPE,
 4 
 5     /** Field declaration (includes enum constants) */
 6     FIELD,
 7 
 8     /** Method declaration */
 9     METHOD,
10 
11     /** Formal parameter declaration */
12     PARAMETER,
13 
14     /** Constructor declaration */
15     CONSTRUCTOR,
16 
17     /** Local variable declaration */
18     LOCAL_VARIABLE,
19 
20     /** Annotation type declaration */
21     ANNOTATION_TYPE,
22 
23     /** Package declaration */
24     PACKAGE,
25 
26     /**
27      * Type parameter declaration
28      *
29      * @since 1.8
30      */
31     TYPE_PARAMETER,
32 
33     /**
34      * Use of a type
35      *
36      * @since 1.8
37      */
38     TYPE_USE,
39 
40     /**
41      * Module declaration.
42      *
43      * @since 9
44      */
45     MODULE
46 }
ElementType
 1 public enum RetentionPolicy {
 2     /**
 3      * Annotations are to be discarded by the compiler.
 4      */
 5     SOURCE,
 6 
 7     /**
 8      * Annotations are to be recorded in the class file by the compiler
 9      * but need not be retained by the VM at run time.  This is the default
10      * behavior.
11      */
12     CLASS,
13 
14     /**
15      * Annotations are to be recorded in the class file by the compiler and
16      * retained by the VM at run time, so they may be read reflectively.
17      *
18      * @see java.lang.reflect.AnnotatedElement
19      */
20     RUNTIME
21 }
RetentionPolicy
posted @ 2020-09-22 19:56  whyha  阅读(145)  评论(1)    收藏  举报