Java 允许我们以自定义注解的形式创建自己的元数据。
我们可以为特定目的创建自己的注解并使用它们。
要创建自定义注解,我们必须使用关键字“@interface”。
下面列出了创建自定义注解时要记住的其他重要事项:
- 每个方法声明都定义了一个注解类型的元素。
- 方法声明不能有任何参数或者 throws 子句。
- 返回类型仅限于上述类型的基元、字符串、类、枚举、注解和数组。
- 方法可以有默认值。
示例
示例 1
// 声明不带任何值的注解DemoAnnotation, public @interface DemoAnnotation { } // 使用注解 @DemoAnnotation public void toggle() { }
示例 2
public @interface Author { String first(); String last(); } // 使用注解 @Author(first = "jackli", last = "Gupta") Book book = new Book();
示例 3
public @interface TravelRequest { int id(); String synopsis(); String engineer() default "[unassigned]"; String date() default "[unimplemented]"; } // 使用注解 @TravelRequest( id = 112233, synopsis = "Teleport me", engineer = "Mr. John Carter", date = "04/01/3007" ) public static void sendMeToMars () { }
日期:2020-09-17 00:09:59 来源:oir作者:oir