使用annotation来描述那些被标注的成员是不稳定的,需要更改
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) public @interface Unstable {}
使用Author这个annotation定义在程序中指出代码的作者
public @interface Author { /** 返回作者名 */ String value(); }
以下的example更加复杂。Reviews annotation类型只有一个成员,但是这个成员的类型是复杂的:由Review annotation组成的数组。Review annotation类型有3个成员:枚举类型成员grade、表示Review名称的字符串类型成员Reviewer、具有默认值的字符串类型成员 Comment。
import java.lang.annotation.*; /** * Reviews annotation类型只有一个成员, * 但是这个成员的类型是复杂的:由Review annotation组成的数组 */ @Retention(RetentionPolicy.RUNTIME) public @interface Reviews { Review[] value(); } /** * Review annotation类型有3个成员: * 枚举类型成员grade、 * 表示Review名称的字符串类型成员Reviewer、 * 具有默认值的字符串类型成员Comment。 */ public @interface Review { // 内嵌的枚举类型 public static enum Grade { EXCELLENT, SATISFACTORY, UNSATISFACTORY }; // 下面的方法定义了annotation的成员 Grade grade(); String reviewer(); String comment() default ""; }
最后,我们来定义一个annotation方法用于罗列出类运行中所有的unchecked异常。这个 annotation类型将一个数组作为了唯一的成员。数组中的每个元素都是异常类。为了加强对未检查的异常(此类异常都是在运行时抛出)进行报告,我们可以在代码中对异常的类型进行限制:
public @interface UncheckedExceptions { Class<? extends RuntimeException>[] value(); }