Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
许多注解会替换代码中的注释。
假设一个软件组传统上在每个类的主体都以注释开始,其中包含提供重要信息的注释:
public class Generation3List extends Generation2List {
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
要使用注解添加此相同元数据,必须先定义 annotation type (注解类型)。这样做的语法是:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
注解类型定义类似于接口定义,其中关键字 interface 前面带有 at 符号(@)(@ = AT,如注解类型)。注解类型是 interface (接口) 的一种形式,将在后面的课程中介绍。目前,你不需要了解接口。
前一个注解定义的主体包含 annotation type element (注解类型元素) 声明,它们看起来很像方法。请注意,他们可以定义可选的默认值。
定义注解类型后,你可以使用该类型的注解,并填入值,如下所示:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
@ClassPreamble 中的信息出现在 Javadoc 生成的文档中,你必须使用 @Documented 来注解 @ClassPreamble 的定义:
// import this to use @Documented
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
// Annotation element definitions
}