Java注解(Annotation)
首先得明白什么是注解?
注解:解释词句的文字;(中文解释)
Annotation: a comment or instruction.(英文注释)
说白了就是让别人看到了就知道啥意思,只不过这里的“别人”是计算机程序而已;
定义
Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。
忽略它的那么多注释,化繁为简,它就只是个普普通通的interface接口而已;
接口的特性
- 接口中的方法可以有参数列表和返回类型,但不能有任何方法体
- 接口中可以包含字段,但是会被隐式的声明为 static 和 final
- 接口中的字段只是被存储在该接口的静态存储区域内,而不属于该接口
- 接口中的方法可以被声明为 public 或不声明,但结果都会按照 public 类型处理
- 当实现一个接口时,需要将被定义的方法声明为 public 类型的,否则为默认访问类型, Java 编译器不允许这种情况
- 如果没有实现接口中所有方法,那么创建的仍然是一个接口
- 扩展一个接口来生成新的接口应使用关键字 extends ,实现一个接口使用 implements
- 接口中的方法是抽象方法(abstract),不能是静态方法(static).接口的所有方法都是抽象的,而抽象方法是没有static,有static的方法是不能override的,所以这样定义接口才有意义
元注解
就像26个英文字母,组成了不同的单词,拥有不同的意思;注解则是四个元注解和注解的类型(ElementType)或生命周期策略(RetentionPolicy)组成各种不同含义的注解;
For example:
@Target
- Indicates the contexts in which an annotation type is applicable.
- 提示上下文哪个注解类型是适用的。
@Inherited
- Indicates that an annotation type is automatically inherited.
- 注解将自动继承。
@Documented
- Indicates that annotations with a type are to be documented by javadoc and similar tools by default.
- 注解将由javadoc和类似的工具默认记录。
@Retention
- Indicates how long annotations with the annotated type are to be retained.
- 提示带注解类型的注解将保留多长时间。
ElementType
The constants of this enumerated type provide a simple classification of the syntactic locations where annotations may appear in a Java program. These constants are used in {@link Target java.lang.annotation.Target} meta-annotations to specify where it is legal to write annotations of a given type.
这些枚举类型的常量给可能出现在Java程序中的注解提供一个简单的语法定位的分类(简化:这些常量给注解提供了一个分类);
这些常量用在元注解(java.lang.annotation.Target)中来指定在哪里编写这些给定类型的注解是合法的。
- ElementType.TYPE:可用于类、接口(包括注解类型(@interface))或者枚举类型定义处
- ElementType.FIELD:可用于变量(包括枚举)定义处
- ElementType.METHOD:可用于方法定义处
- ElementType.PARAMETER:可用于形式参数定义处
- ElementType.CONSTRUCTOR:可用于构造方法定义处
- ElementType.LOCAL_VARIABLE:可用于本地变量定义处
- ElementType.ANNOTATION_TYPE:可用于注解定义处
- ElementType.PACKAGE:可用于包定义处
RetentionPolicy
Annotation retention policy. The constants of this enumerated type describe the various policies for retaining annotations. They are used in conjunction with the {@link Retention} meta-annotation type to specify how long annotations are to be retained.
注解的生命周期策略;这些枚举类型的常量用于描述各种注解的生命周期策略;它们和元注解类型被用来指定注解将存活多久。
- RetentionPolicy.SOURCE:当前注解编译期可见,不会写入 class 文件
- RetentionPolicy.CLASS:类加载阶段丢弃,会写入 class 文件
- RetentionPolicy.RUNTIME:永久保存,可以反射获取
总结
很多问题都可以化繁为简,把复杂难以理解的东西变成容易理解的东西,回到它最初的本质。