这篇Java教程基于JDK1.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
}
为了能够添加同样的元数据,首先你要定义一个注解类型,如下所示:
@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关键字前面有一个@符号。注解类型其实是接口的一种形式,这个将在后续教程中详述。现在,你不需要理解接口。
上文注解定义中包含注解类型元素的声明,看起来像方法。注意它们可以定义可选的默认值。
注解定义之后,你就可以使用该类型的注解,如下所示:
@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文档中,你必须在@ClassPreamble注解定义上使用@Documented注解。
// import this to use @Documented
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
// Annotation element definitions
}