74.md 2.0 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8
# 声明注解类型

> 原文: [https://docs.oracle.com/javase/tutorial/java/annotations/declaring.html](https://docs.oracle.com/javase/tutorial/java/annotations/declaring.html)

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

假设一个软件组传统上启动每个类的主体,并提供重要信息的注解:

W
wizardforcel 已提交
9
```java
W
init  
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
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

}

```

W
wizardforcel 已提交
25
要使用注解添加相同的元数据,必须首先定义*注解类型*。这样做的语法是:
W
init  
wizardforcel 已提交
26

W
wizardforcel 已提交
27
```java
W
init  
wizardforcel 已提交
28 29 30 31 32 33 34 35 36 37 38 39
@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();
}

```

W
wizardforcel 已提交
40
注解类型定义类似于接口定义,其中关键字`interface`前面带有 at 符号(`@`)(@ = AT,如注解类型)。注解类型是*接口*的一种形式,将在后面的课程中介绍。目前,您不需要了解接口。
W
init  
wizardforcel 已提交
41

W
wizardforcel 已提交
42
前一个注解定义的主体包含*注解类型元素*声明,它看起来很像方法。请注意,他们可以定义可选的默认值。
W
init  
wizardforcel 已提交
43 44 45

定义注解类型后,您可以使用该类型的注解,并填入值,如下所示:

W
wizardforcel 已提交
46
```java
W
init  
wizardforcel 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
@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:

W
wizardforcel 已提交
68
```java
W
init  
wizardforcel 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81
// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions

}

```

* * *