1.注解概念
An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate
翻译:
注解是一种可以添加到java源代码中的元数据形式。类,方法,变量,参数和包都可以被添加注解。注解对被注解的代码没有直接的影响
- 注解是一种元数据形式类似类,枚举,接口
- 注解修饰类,方法,变量,参数和包
- 注解不会对被注解的代码产生直接影响,配合反射对被注解都得代码产生影响
2.自定义注解
语法:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface custom{
String name() default "";
}
@interface
: @interface 定义注解时,意味着它实现了 java.lang.annotation.Annotation 接口,即该注解就是一个Annotation
@Target
:表示注解用在什么地方,枚举参数ElementType的包括:
-
CONSTRUCTOR:构造函数
-
TYPE:类,接口,枚举和注解
-
FIELD:字段声明(包括枚举常量)
-
METHOD:方法
-
PARAMETER:参数
-
PACKAGE:包
-
LOCAL_VARIABLE:局部变量
-
ANNOTATION_TYPE:注解
@Retention
:注解的生命周期,RetentionPolicy参数包括: -
SOURCE:注解仅在java源码中,在编译器编译时被丢弃
-
CLASS:默认保留策略,注解被编译器编译存在于class字节码文件中,但是运行时会被JVM丢弃
-
RUNTIME:注解被编译器编译编译保存在class字节码文件中,运行时保留在JVM中可以通过反射获得(实际开发中自定义注解使用此类型)
@Documented
:表示自定义注解是否生成到javaDoc文档中
@Inherited
:允许子类集成父类中的注解
3.常用注解
@Override:方法重载
@SuppressWarnings - 指示编译器去忽略注解中声明的警告。
@Deprecated - 标记过时方法。如果使用该方法,会报编译警告。