Documentation

The Java™ Tutorials
Hide TOC
Annotations Basics批注基础
Trail: Learning the Java Language
Lesson: Annotations

Annotations Basics批注基础

The Format of an Annotation批注的格式

In its simplest form, an annotation looks like the following:批注的最简单形式如下所示:

@Entity

The at sign character (@) indicates to the compiler that what follows is an annotation.at符号字符(@)向编译器指示后面是批注。In the following example, the annotation's name is Override:在以下示例中,批注的名称为Override

@Override
void mySuperMethod() { ... }

The annotation can include elements, which can be named or unnamed, and there are values for those elements:批注可以包括可以命名或未命名的元素,这些元素有以下值:

@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass { ... }

or或:

@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

If there is just one element named value, then the name can be omitted, as in:如果只有一个名为value的元素,则可以省略该名称,如下所示:

@SuppressWarnings("unchecked")
void myMethod() { ... }

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.如果批注没有元素,则可以省略括号,如前面的@Override示例所示。

It is also possible to use multiple annotations on the same declaration:也可以在同一声明上使用多个批注:

@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

If the annotations have the same type, then this is called a repeating annotation:如果批注具有相同的类型,则这称为重复批注:

@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }

Repeating annotations are supported as of the Java SE 8 release.从Java SE 8版本开始,就支持重复批注。For more information, see Repeating Annotations.有关详细信息,请参阅重复批注

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API.批注类型可以是java SE API的java.langjava.lang.annotation包中定义的类型之一。In the previous examples, Override and SuppressWarnings are predefined Java annotations.在前面的示例中,OverrideSuppressWarning是预定义的Java批注。It is also possible to define your own annotation type.也可以定义自己的批注类型。The Author and Ebook annotations in the previous example are custom annotation types.上一个示例中的AuthorEbook批注是自定义批注类型。

Where Annotations Can Be Used可以使用批注的位置

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements.批注可以应用于声明:类、字段、方法和其他程序元素的声明。When used on a declaration, each annotation often appears, by convention, on its own line.在声明中使用时,按照惯例,每个批注通常显示在自己的行上。

As of the Java SE 8 release, annotations can also be applied to the use of types.从Java SE 8版本开始,批注也可以应用于类型的使用Here are some examples:以下是一些例子:

This form of annotation is called a type annotation.这种形式的批注称为类型批注For more information, see Type Annotations and Pluggable Type Systems.有关详细信息,请参阅类型批注和可插入类型系统


Previous page: Annotations
Next page: Declaring an Annotation Type