Java注解
2020-10-01 本文已影响0人
我菠菜今天就是要为所欲为
本文以常用注解@Override
为例,旨在描述清注解的作用与使用方法,并非详细讲解每一个注解。
@Override
的作用
通知编译器,使用该注解标记的方法必须重写父类或Object类的同名方法。
首先看一下源码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
- 这里使用
@interface
注明这是一个注解类。 - 这个注解被
@Target
、@Retention
标记。
元注解
元注解是注解的注解,一般用来说明注解的作用域与作用时期。
以上面的@Target
、@Retention
为例,
@Retention
- 作用是用于提示注解被保留多长时间
/**
* Indicates how long annotations with the annotated type are to
* be retained. If no Retention annotation is present on
* an annotation type declaration, the retention policy defaults to
* RetentionPolicy.CLASS.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
这个注解的取值有三种,分别是
-
SOURCE
保留至源码级别,不被编译 -
CLASS
保留至字节码级别,不被虚拟机识别 -
RUNTIME
保留至运行时,可以被反射读取
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,
/**
* 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.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Target
- 作用是用于提示该注解使用的地方
package java.lang.annotation;
/**
* Indicates the contexts in which an annotation type is applicable. The
* declaration contexts and type contexts in which an annotation type may be
* applicable are specified in JLS 9.6.4.1, and denoted in source code by enum
* constants of java.lang.annotation.ElementType
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 9.7.4 Where Annotations May Appear
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
这个注解的取值有8种,分别是:
- 类,接口,注解,枚举
- 属性
- 方法
- 参数
- 构造函数
- 局部变量
- 注解类型
- 包
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
* @since 1.8
*/
TYPE_USE
}
那么我们再回头理解@Override
注解,这个注解只在源代码级别生效,并且只能标记在方法上。
完