Annotation

来源:互联网 发布:pxcook像素大厨 mac版 编辑:程序博客网 时间:2024/05/01 22:29

定制注释类型

    好的,让我们创建一个自己的注释类型(annotation type )吧。它类似于新创建一个接口类文件,但为了区分,我们需要将它声明为@interface, 如下例:

public @interface NewAnnotation {}


使用定制的注释类型

    我们已经成功地创建好一个注释类型NewAnnotation ,现在让我们来尝试使用它吧,如果你还记得本文的第一部分,那你应该知道他是一个标记注释,使用也很容易,如下例:

public class AnnotationTest {     @NewAnnotation    public static void main(String[] args) {    }}
 

添加变量

    J2SE 5.0 里,我们了解到内置注释@SuppressWarnings() 是可以使用参数的,那么自定义注释能不能定义参数个数和类型呢?答案是当然可以,但参数类型只允许为基本类型、String 、Class 、枚举类型等,并且参数不能为空。我们来扩展NewAnnotation ,为之添加一个String 类型的参数,示例代码如下:

public @interface NewAnnotation {    String value();}    使用该注释的代码如下:正如你所看到的,该注释的使用有两种写法,这也是在之前的文章里所提到过的。如果你忘了这是怎么回事,那就再去翻翻吧。public class AnnotationTest {    @NewAnnotation("Just a Test.")    public static void main(String[] args) {        sayHello();    }       @NewAnnotation(value="Hello NUMEN.")    public static void sayHello() {        // do something    }}

 

为变量赋默认值

    我们对Java 自定义注释的了解正在不断的增多,不过我们还需要更过,在该条目里我们将了解到如何为变量设置默认值,我们再对NewAnnotaion 进行修改,看看它会变成什么样子,不仅参数多了几个,连类名也变了。但还是很容易理解的,我们先定义一个枚举类型,然后将参数设置为该枚举类型,并赋予默认值。

public @interface Greeting {     public enum FontColor {RED, GREEN, BLUE};     String name();     String content();       FontColor fontColor() default FontColor.BLUE;}

 

限定注释使用范围

    当我们的自定义注释不断的增多也比较复杂时,就会导致有些开发人员使用错误,主要表现在不该使用该注释的地方使用。为此,Java 提供了一个ElementType 枚举类型来控制每个注释的使用范围,比如说某些注释只能用于普通方法,而不能用于构造函数等。下面是Java 定义的ElementType 枚举:

package java.lang.annotation; public enum ElementType {  TYPE,         // Class, interface, or enum (but not annotation)  FIELD,        // Field (including enumerated values)  METHOD,       // Method (does not include constructors)  PARAMETER,        // Method parameter  CONSTRUCTOR,      // Constructor  LOCAL_VARIABLE,   // Local variable or catch clause  ANNOTATION_TYPE,  // Annotation Types (meta-annotations)  PACKAGE       // Java package}

    下面我们来修改Greeting 注释,为之添加限定范围的语句,这里我们称它为目标(Target )使用方法也很简单,如下:

@Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })public @interface Greeting {}

正如上面代码所展示的,我们只允许Greeting 注释标注在普通方法和构造函数上,使用在包申明、类名等时,会提示错误信息。

 

注释保持性策略

public enum RetentionPolicy {  SOURCE,// Annotation is discarded by the compiler  CLASS,// Annotation is stored in the class file, but ignored by the VM  RUNTIME// Annotation is stored in the class file and read by the VM}

    RetentionPolicy 的使用方法与ElementType 类似,简单代码示例如下:

@Retention(RetentionPolicy.RUNTIME)@Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })

 

文档化功能

    Java 提供的Documented 元注释跟Javadoc 的作用是差不多的,其实它存在的好处是开发人员可以定制Javadoc 不支持的文档属性,并在开发中应用。它的使用跟前两个也是一样的,简单代码示例如下:

@Documented@Retention(RetentionPolicy.RUNTIME)@Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })public @interface Greeting {}
 

值得大家注意的是,如果你要使用@Documented 元注释,你就得为该注释设置RetentionPolicy.RUNTIME 保持性策略。为什么这样做,应该比较容易理解,这里就不提了。

0 0
原创粉丝点击