注解定义
通过官方描述得出以下结论:
1.注解是一种元数据形式。即注解是属于java的一种数据类型,和类、接口、数组、枚举类似。
2.注解用来修饰,类、方法、变量、参数、包。
3.注解不会对所修饰的代码产生直接的影响。
注解又许多用法,其中有:
1.为编译器提供信息 - 注解能被编译器检测到错误或抑制警告。
2.编译时和部署时的处理 - 软件工具能处理注解信息从而生成代码,XML文件等等。
3.运行时的处理 - 有些注解在运行时能被检测到。
注解的作用:
1.生成文档。
2.跟踪代码依赖性,实现替代配置文件功能。
3.在编译时进行格式检查。
基本语法:
使用的关键字有所不同@interface。在底层实现上,所有定义的注解都会自动继承java.lang.annotation.Annotation接口。
public @interface MyAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface MyAnnotation {
public int age() default 18;
String name() ;
String [] books();
}
注解定义注解类型元素时需要注意如下几点:
1.访问修饰符必须为public,不写默认为public;
2.该元素的类型只能是基本数据类型、String、Class、枚举类型、注解类型(体现了注解的嵌套效果)以及上述类型的一位数组;
3.该元素的名称一般定义为名词,如果注解中只有一个元素,请把名字起为value(后面使用会带来便利操作);
4.()不是定义方法参数的地方,也不能在括号中定义任何参数,仅仅只是一个特殊的语法;
5.default代表默认值,值必须和第2点定义的类型一致;
6.如果没有默认值,代表后续使用注解时必须给该类型元素赋值。
常用的元注解
@Document
是被用来指定自定义注解是否能随着被定义的java文件生成到JavaDoc文档当中。
@Target
是专门用来限定某个自定义注解能够被应用在哪些Java元素上面的,不定义说明可以放在任何元素上。
使用枚举类ElementType来定义
public enum ElementType {
/** 类,接口(包括注解类型)或枚举的声明 */
TYPE,
/** 属性的声明 */
FIELD,
/** 方法的声明 */
METHOD,
/** 方法形式参数声明 */
PARAMETER,
/** 构造方法的声明 */
CONSTRUCTOR,
/** 局部变量声明 */
LOCAL_VARIABLE,
/** 注解类型声明 */
ANNOTATION_TYPE,
/** 包的声明 */
PACKAGE
}
@Retention
即用来修饰自定义注解的生命周期。
使用了RetentionPolicy枚举类型定义了三个阶段
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
* (注解将被编译器丢弃)
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
* (注解将被编译器记录在class文件中,但在运行时不会被虚拟机保留,这是一个默认的行为)
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
* (注解将被编译器记录在class文件中,而且在运行时会被虚拟机保留,因此它们能通过反射被读取到)
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Inherited
允许子类继承父类中的注解
反射操作AnnotatedElement实现类获取注解
方法

AnnotatedElement实现类

java 注解知识脑图

网友评论