声明 注解 类型

许多 注解 会替换代码中的 注解。

假设一个软件组传统上以提供重要信息的 注解 开始每个类的主体:

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定义,在该interface定义中,关键字interface前面带有 at 符号(@)(@ = AT,与注解类型相同)。注解 类型是一种interface形式,将在以后的类中介绍。目前,您不需要了解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

}

Note:

要使@ClassPreamble中的信息出现在 Javadoc 生成的文档中,您必须使用@Documented注解 对@ClassPreamble定义进行 注解:

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

// Annotation element definitions

}