The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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 }
@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
}