Documentation

The Java™ Tutorials
Hide TOC
Declaring an Annotation Type声明批注类型
Trail: Learning the Java Language
Lesson: Annotations

Declaring an Annotation Type声明批注类型

Many annotations replace comments in code.许多批注替换代码中的批注。

Suppose that a software group traditionally starts the body of every class with comments providing important information:假设软件组传统上以提供重要信息的批注开始每个类的主体:

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

}

To add this same metadata with an annotation, you must first define the annotation type.要使用批注添加相同的元数据,必须首先定义批注类型The syntax for doing this is:执行此操作的语法是:

@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();
}

The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign (@) (@ = AT, as in annotation type).批注类型定义看起来类似于接口定义,其中关键字interface前面有at符号(@)(@=AT,如批注类型中的那样)。Annotation types are a form of interface, which will be covered in a later lesson.批注类型是接口的一种形式,将在后面的课程中介绍。For the moment, you do not need to understand interfaces.目前,您不需要理解接口。

The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.上一个批注定义的主体包含批注类型元素声明,这些声明看起来很像方法。请注意,它们可以定义可选的默认值。

After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:定义批注类型后,可以使用该类型的批注,并填充值,如下所示:

@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: To make the information in @ClassPreamble appear in Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:要使@ClassPreamble中的信息出现在Javadoc生成的文档中,必须使用@Documented批注批注@ClassPreamble定义:
// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
   
}


Previous page: Annotations Basics
Next page: Predefined Annotation Types