许多注解替换代码中的注释。
假设一个软件组传统上开始每个类的正文,提供重要信息:
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关键字之前写上符号@,(@=AT,注解类型)注释类型是一种接口形式,将在后面的课程中讨论。目前,您不需要了解接口。
在前面定义的注解体中包含注解类型元素的声明,像方法一样,注意,在这里它们可以定义可选的默认值。
在注解类型被定义后,你可以使用这个注解,加上属性的值,如下:
@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
}