注解(三):声明一个注解类型

很多注解替代了代码中的注释。

想象一个软件团队习惯用提供重要信息的注释开始每个类体:

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 生成的文档中,必须用 @Documented 注解 @ClassPreamble 的定义:
// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

 // Annotation element definitions

}