自定义注解

来源:互联网 发布:mac netflix 编辑:程序博客网 时间:2024/04/30 05:17
@Documented,@Retention,@Target,@Inherited

1. 编写自定义@Todo注解
经常我们在写程序时,有时候有些功能在当前的版本中并不提供,或由于某些其它原因,有些方法没有完成,而留待以后完成,我们在javadoc中用@TODO来描述这一行为,下面用java注解来实现。

public @interface Todo { } // Todo.java

如果你想让这个注解类型能够自省的话,给它加上@Todo注解,写法如下:

@Todo
public @interface Todo{ }


下面我们给这个注解接受参数的能力,代码如下:
@Todo("Just articleware")public @interface Todo{public enum Priority { LOW, MEDIUM, HIGH }String value();String[] owners() default "";Priority priority() default Priority.MEDIUM;}

注意注解类性所能接受的参数类型有着严格的规则:
a. 参数类型只能是:primitive, String, Class, enum, annotation, 或者是数组;
b. 参数值不能为空,因此每一个参数值都要定义一个缺省值;
c. 名字为value的参数可以用简便的方法来设置;
d. 参数的写法如同写简单方法(看如上代码),不允许加入参数,不允许有throws子句等。

在上面的代码中,我们为@Todo定义了3个参数, 分别是value, owners, priority. 注意:由于value的特殊性,它的的却省值可以由上面代码中的"Just articleware"来定义,当然你也可以单独写一个缺省值。

下面看一个应用@Todo注解的例子:
@Todo(value="Class scope",priority=Unfinished.Priority.LOW)public class TodoDemo {@Todo("Constructor scope")//通过快捷方式,设置value的值public TodoDemo() { }@Todo(owner="Jason", value="Method scope")public void foo() { }}

上面的代码很简单,不多介绍。

下面我们想让@Todo不能应用在fields, parameters, 或者local variables(因为这对我们来说没有意义);它应当可以出现在javadoc中;在运行是具有持久性。要实现这些特性,就需要annotation包的支持啦。

2. 应用annotation包的支持

1)@Documented
类和方法的annotation缺省情况下是会出现在javadoc中的,为了加入这个性质我们用@Documented
应用代码如下(简单,不多介绍):
package com.robin;import java.lang.annotation.*;@Todo("Just articleware")@Documentedpublic @interface Todo{ ...


2)@Retention
用来表明你的annotation的有效期,可以有三种选择(如图所示):

以下示例代码应用RUNTIME策略
package com.robin;import java.lang.annotation.*;@Todo("Just articleware")@Documented@Retention(RetentionPolicy.RUNTIME)public @interface Todo{ ...

3) @Target
@Target注解表明某个注解应用在哪些目标上,可选择如下范围:
  • ElementType.TYPE (class, interface, enum)
  • ElementType.FIELD (instance variable)
  • ElementType.METHOD ElementType.PARAMETER
  • ElementType.CONSTRUCTOR
  • ElementType.LOCAL_VARIABLE
  • ElementType.ANNOTATION_TYPE (应用于另一个注解上)
  • ElementType.PACKAGE

按我们的功能要求,代码如下:
package com.robin;import java.lang.annotation.*;@Todo("Just articleware")@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,ElementType.PACKAGE})public @interface Todo{ ...

4) @Inherited
@Inherited表明是否一个使用某个annotation的父类可以让此annotation应用于子类。
示例代码如下:
package com.robin;import java.lang.annotation.*;@Todo("Just articleware")@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,ElementType.PACKAGE})@Inheritedpublic @interface Todo{public enum Priority { LOW, MEDIUM, HIGH }String value();String[] owners() default "";Priority priority() default Priority.MEDIUM;}
0 0
原创粉丝点击