深入分析 java注解。让你快走一步!
java元注解
元注解作用是负责注解其他注解,java5.0定义了四个标准的元注解。包括:@Target、@Documented、@Retention、@Inherit。
@Target注解:它用于描述注解可以修饰的类型。可以修饰的类型为:TYPE(类、接口、枚举)、FIELD、METHOD(方法声明)、PARAMETER(参数)、CONSTRUCTOR(构造方法)、LOCAL_VARIABLE(本地变量)、ANNOTATION_TYPE(注解类型声明)、PACKAGE(包)。
其代码如下所示:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target{
ElementType[] value();
}
@Retention注解:用于表示该注解的作用阶段。其参数可以取RetentionPolicy中的值。如:
SOURCE:作用于源代码中,编译阶段被去除。
CLASS:可以被编译进Class文件中,但是虚拟机对其忽略。
RUNTIME:可以被编译进Class文件,虚拟机在运行期使用。
其代码为:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention{
RetentionPolicy value();
}
@Documented注解:用于在生成API文档的时候,使得该注解可以呈现在使用该注解的API上。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Document{
}
@Inherit注解:是一个标记注解,用于描述一个注解可以被继承。如果一个类使用了(@Interit标注的注解)的话,那么该注解可以被该类的子类继承。
如果使用反射去查找一个标注了@Inherit注解的类的时候,反射代码会检查该类及其父类,直到找到标注了该注解的顶层类。
其代码如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited{
}
自定义注解
根据上面的元注解我们可以定义自己的注解,注解在定义的时候,可以指定其不同的参数,以及该参数的默认值。
这里自己定义了一个注解,其中添加了两个参数,分别是name和age并设置了默认值。
根据上面定义的注解,其保留到运行时,且标注于方法上。
下面针对该注解进行测试。
输出结果如下:
注解本质
本质上注解会被编译为继承了(Annotation接口)的接口。
反编译上面的PersonAnno.class可以看到代码如下:
Compiled from "PersonAnno.java"
public interface com,wy.annotation.PersonAnno extends java.lang.annotation.Annotation{
public abstract java.lang.String name();
public abstract int age();
}
从上面的反编译后的代码可以看出注解实际上被编译为接口了。
/**
* The common interface extended by all annotation types. Note that an
* interface that manually extends this one does <i>not</i> define
* an annotation type. Also note that this interface does not itself
* define an annotation type.
*
* More information about annotation types can be found in section 9.6 of
* <cite>The Java™ Language Specification</cite>.
*
* @author Josh Bloch
* @since 1.5
*/public interface Annotation {}1234567891011121312345678910111213
这里Annotation接口中已经给出了说明,该接口被所有的注解类型的接口继承。