Java注解
annotation
,又被称为Java标注,是JDK5.0引入的一种注释机制。
Java语言的类、方法、变量、参数和包都可以被标注,和javadoc不一样,Java注解可以通过反射获取标注内容,编译器生成类文件时,注解可以嵌入字节码中
。也可以支持自定义Java注解。
Java注解
内置的注解
Java定义了一套注解,共有7个,3个在java.lang
中,另外在java.lang.annotation
中;
作用在代码的注解
- @Override - 检查该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
- @Deprecated - 标记过时方法。如果使用该方法,会报编译警告。
- @SuppressWarnings - 指示编译器去忽略注解中声明的警告。
作用在其他注解的注解,也称之为元注解是:
- @Retention - 标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。
- @Documented - 标记这些注解是否包含在用户文档中。
- @Target - 标记这个注解应该是哪种 Java 成员。
- @Inherited - 标记这个注解是继承于哪个注解类(默认 注解并没有继承于任何子类)。
Java7中,额外添加了3个注解:
- @SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
- @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
- @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。
1、annotation架构
如图所示:
由图可得:
- 1 个 Annotation 和 1 个 RetentionPolicy 关联。
可以理解为:每1个Annotation对象,都会有唯一的RetentionPolicy属性。 - 1 个 Annotation 和 1~n 个 ElementType 关联。
可以理解为:对于每 1 个 Annotation 对象,可以有若干个 ElementType 属性。 - Annotation 有许多实现类,包括:Deprecated, Documented, Inherited, Override 等等。
Annotation 的每一个实现类,都 “和 1 个 RetentionPolicy 关联" 并且 " 和 1~n 个 ElementType 关联”。
2、annotation组成部分
在Java annotation组成中,由三个重要部分,分别是:
package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
ElementType.java代码:
package java.lang.annotation;
public enum ElementType {
TYPE, /* 类、接口(包括注释类型)或枚举声明 */
FIELD, /* 字段声明(包括枚举常量) */
METHOD, /* 方法声明 */
PARAMETER, /* 参数声明 */
CONSTRUCTOR, /* 构造方法声明 */
LOCAL_VARIABLE, /* 局部变量声明 */
ANNOTATION_TYPE, /* 注释类型声明 */
PACKAGE /* 包声明 */
}
RetentionPolicy.java代码:
package java.lang.annotation;
public enum RetentionPolicy {
SOURCE, /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了 */
CLASS, /* 编译器将Annotation存储于类对应的.class文件中。默认行为 */
RUNTIME /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}
由源码分析可得如下:
- Annotation 就是个接口。
*每 1 个 Annotation" 都与 1 个 RetentionPolicy关联
,并且与 “1~n 个 ElementType” 关联。可以通俗的理解为:每 1 个 Annotation 对象,都会有唯一的 RetentionPolicy 属性;至于 ElementType 属性,则有 1~n 个。 - ElementType 是 Enum 枚举类型,它用来指定 Annotation 的类型。
每 1 个 Annotation都与 1~n 个 ElementType关联
。当 Annotation 与某个 ElementType 关联时,就意味着:Annotation有了某种用途。例如,若一个 Annotation 对象是 METHOD 类型,则该 Annotation 只能用来修饰方法。 - RetentionPolicy 是 Enum 枚举类型,它用来指定 Annotation 的策略。通俗点说,就是不同 RetentionPolicy 类型的 Annotation 的作用域不同。
每 1 个 Annotation" 都与 "1 个 RetentionPolicy" 关联
。
- 若 Annotation 的类型为 SOURCE,则意味着:Annotation 仅存在于编译器处理期间,编译器处理完之后,该 Annotation 就没用了。 例如,@Override 标志就是一个 Annotation。当它修饰一个方法的时候,就意味着该方法覆盖父类的方法;并且在编译期间会进行语法检查!编译器处理完后,@Override就没有任何作用了。
- 若Annotation 类型是CLASS,则意味着:编译器把Annotation 存储与类对应的.class文件中,是Annotation 的默认行为。
- 若Annotation 类型是RUNTIME,则意味着:编译器把Annotation 存储class文件中,并且由JVM读入。
3、Java自带的Annotation
1)Annotation 通用定义
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1 {
}
解释如下:
定义一个Annotation ,名称是MyAnnotation1。定义了 MyAnnotation1 之后,我们可以在代码中通过 @MyAnnotation1来使用它。 其它的,@Documented,@Target,@Retention,@interface 都是来修饰 MyAnnotation1的。
- @interface
使用 @interface 定义注解时,意味着它实现了 java.lang.annotation.Annotation 接口,即该注解就是一个Annotation。
定义 Annotation 时,@interface 是必须的。
注意:它和我们通常的 implemented 实现接口的方法不同。Annotation 接口的实现细节都由编译器完成。通过 @interface 定义注解后,该注解不能继承其他的注解或接口。
-
@Documented
类和方法的 Annotation 在缺省情况下是不出现在 javadoc 中的。如果使用 @Documented 修饰该 Annotation,则表示它可以出现在 javadoc 中。
定义 Annotation 时,@Documented 可有可无;若没有定义,则 Annotation 不会出现在 javadoc 中。 -
@Target(ElementType.TYPE)
@Target(ElementType.TYPE) 的意思就是指定该 Annotation 的类型是 ElementType.TYPE。这就意味着,MyAnnotation1 是来修饰类、接口(包括注释类型)或枚举声明的注解。
定义 Annotation 时,@Target 可有可无。若有 @Target,则该 Annotation 只能用于它所指定的地方;若没有 @Target,则该 Annotation 可以用于任何地方。 -
@Retention(RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME) 的意思就是指定该 Annotation 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将该 Annotation 信息保留在 .class 文件中,并且能被虚拟机读取。
定义 Annotation 时,@Retention 可有可无。若没有 @Retention,则默认是 RetentionPolicy.CLASS。
@Deprecated -- @Deprecated 所标注内容,不再被建议使用。
@Override -- @Override 只能标注方法,表示该方法覆盖父类中的方法。
@Documented -- @Documented 所标注内容,可以出现在javadoc中。
@Inherited -- @Inherited只能被用来标注“Annotation类型”,它所标注的Annotation具有继承性。
@Retention -- @Retention只能被用来标注“Annotation类型”,而且它被用来指定Annotation的RetentionPolicy属性。
@Target -- @Target只能被用来标注“Annotation类型”,而且它被用来指定Annotation的ElementType属性。
@SuppressWarnings -- @SuppressWarnings 所标注内容产生的警告,编译器会对这些警告保持静默。
2)@Deprecated
定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}
说明:
- @interface – 它的用来修饰 Deprecated,意味着 Deprecated 实现了 java.lang.annotation.Annotation 接口;即 Deprecated 就是一个注解。
- @Documented – 它的作用是说明该注解能出现在 javadoc 中。
- @Retention(RetentionPolicy.RUNTIME) – 它的作用是指定 Deprecated 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将Deprecated 的信息保留在 .class 文件中,并且能被虚拟机读取。
- @Deprecated – 所标注内容,不再被建议使用。
package annotation;
import java.util.Calendar;
import java.util.Date;
public class DeprecatedTest {
@Deprecated
private static void getString() {
System.out.println("Deprecated test");
}
private static void getString2() {
System.out.println("normal method");
}
@Deprecated
private static void testDate() {
Date date = new Date(113, 8, 25);
System.out.println(date.getYear());
}
private static void testCalendar() {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));
}
public static void main(String[] args) {
getString();
getString2();
testDate();
testCalendar();
}
}
2)@Inherited
定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
- @interface – 它的用来修饰 Inherited,意味着
Inherited 实现了 java.lang.annotation.Annotation 接口;即 Inherited 就是一个注解
。 - @Documented – 它的作用是说明该注解能出现在 javadoc 中。
- @Retention(RetentionPolicy.RUNTIME) – 它的作用是指定 Inherited 的策略是 RetentionPolicy.RUNTIME。这就意味着,
编译器会将 Inherited 的信息保留在 .class 文件中,并且能被虚拟机读取
。 - @Target(ElementType.ANNOTATION_TYPE) – 它的作用是指定 Inherited 的类型是 ANNOTATION_TYPE。这就意味着,@Inherited 只能被用来标注
Annotation 类型
。
package annotation;
import java.lang.annotation.*;
/**
* 自定义的Annotation。
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface Inheritable {
}
@Inheritable
class InheritableFather {
public InheritableFather() {
// InheritableBase是否具有 Inheritable Annotation
System.out.println("InheritableFather:" + InheritableFather.class.isAnnotationPresent(Inheritable.class));
}
}
/**
* InheritableSon 类只是继承于 InheritableFather,
*/
public class InheritableSon extends InheritableFather {
public InheritableSon() {
// 调用父类的构造函数
super();
// InheritableSon类是否具有 Inheritable Annotation
System.out.println("InheritableSon:" + InheritableSon.class.isAnnotationPresent(Inheritable.class));
}
public static void main(String[] args) {
InheritableSon is = new InheritableSon();
}
}
3)@SuppressWarnings
定义如下:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
- @interface – 它的用来修饰 SuppressWarnings,意味着
SuppressWarnings 实现了 java.lang.annotation.Annotation 接口;即 SuppressWarnings 就是一个注解
。 - @Retention(RetentionPolicy.SOURCE) – 它的作用是指定
SuppressWarnings 的策略是 RetentionPolicy.SOURCE
。这就意味着,SuppressWarnings 信息仅存在于编译器处理期间,编译器处理完之后 SuppressWarnings 就没有作用了。 - @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) – 它的作用是指定
SuppressWarnings 的类型同时包括TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE
。 - String[] value():意味着,SuppressWarnings 能指定参数。
- SuppressWarnings 的作用是,让编译器对"它所标注的内容"的某些警告保持静默。
import java.util.Date;
public class SuppressWarningTest {
//@SuppressWarnings(value={"deprecation"})
public static void doSomething(){
Date date = new Date(113, 8, 26);
System.out.println(date);
}
public static void main(String[] args) {
doSomething();
}
}
补充:SuppressWarnings 常用的关键字的表格~
deprecation -- 使用了不赞成使用的类或方法时的警告
unchecked -- 执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
fallthrough -- 当 Switch 程序块直接通往下一种情况而没有 Break 时的警告。
path -- 在类路径、源文件路径等中有不存在的路径时的警告。
serial -- 当在可序列化的类上缺少 serialVersionUID 定义时的警告。
finally -- 任何 finally 子句不能正常完成时的警告。
all -- 关于以上所有情况的警告。
4、Annotation 的作用
Annotation 是一个辅助类,它在 Junit、Struts、Spring 等工具框架中被广泛使用。
1)编译检查
Annotation具有让编译器进行编译检查的作用。
- 若某个方法被 @Override 的标注,则意味着该方法会覆盖父类中的同名方法。如果有方法被 @Override 标示,但父类中却没有"被 @Override 标注"的同名方法,则编译器会报错。示例如下:
public class OverrideTest {
/**
* toString() 在java.lang.Object中定义;
* 因此,这里用 @Override 标注是对的。
*/
@Override
public String toString(){
return "Override toString";
}
/**
* getString() 没有在OverrideTest的任何父类中定义;
* 但是,这里却用 @Override 标注,因此会产生编译错误!
*/
@Override
public String getString(){
return "get toString";
}
public static void main(String[] args) {
}
}
2)反射中使用Annotation
在反射的 Class, Method, Field 等函数中,有许多于 Annotation 相关的接口。
package annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Annotation在反射函数中的使用示例
*/
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String[] value() default "unknown";
}
class Person {
/**
* empty()方法同时被 "@Deprecated" 和 "@MyAnnotation(value={"a","b"})"所标注
* (01) @Deprecated,意味着empty()方法,不再被建议使用
* (02) @MyAnnotation, 意味着empty() 方法对应的MyAnnotation的value值是默认值"unknown"
*/
@MyAnnotation
@Deprecated
public void empty() {
System.out.println("\nempty");
}
/**
* sombody() 被 @MyAnnotation(value={"girl","boy"}) 所标注,
*
* @MyAnnotation(value={"girl","boy"}), 意味着MyAnnotation的value值是{"girl","boy"}
*/
@MyAnnotation(value = {"girl", "boy"})
public void somebody(String name, int age) {
System.out.println("\nsomebody: " + name + ", " + age);
}
}
public class AnnotationTest {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//新建Person
Person person = new Person();
//获取Person的class实例
Class<Person> c = Person.class;
//获取somebody()方法的method实例
Method m = c.getMethod("somebody", String.class, int.class);
//执行方法
m.invoke(person, "lily", 18);
iteratorAnnotations(m);
//获取somebody的method实例
Method mEmpty = c.getMethod("empty");
//执行方法
mEmpty.invoke(person);
iteratorAnnotations(mEmpty);
}
public static void iteratorAnnotations(Method method) {
//判定somebody方法是否包含了MyAnnotation注解
if (method.isAnnotationPresent(MyAnnotation.class)) {
//获取方法的MyAnnotation注解实例
MyAnnotation m = method.getAnnotation(MyAnnotation.class);
//获取m的数值,并且打印出来
String[] values = m.value();
for (String str : values) {
System.out.printf(str + " ");
}
System.out.println();
}
//获取方法上的所有注解 打印结果
Annotation[] a = method.getAnnotations();
for (Annotation annotation : a) {
System.out.println(annotation);
}
}
}
3)根据Annotation 生成doc
通过给 Annotation 注解加上 @Documented 标签,能使该 Annotation 标签出现在 javadoc 中。
4)可以协助查看代码
通过 @Override, @Deprecated 等,我们能很方便的了解程序的大致结构。
另外,我们也可以通过自定义 Annotation 来实现一些功能。