声明注释类型---使用@(annotation)

在对类结构进行注释时,传统的方法是对每一个成员变量都要进行注释。例如下面这种情况,非常的麻烦。

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
}

而一种更简单的方式就是定义一个annotation结构的注释。

@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();
}

这种定义结构和接口的定义方法有些类似,这里的关键字@是定义annotation的标志。
在定义完annotation后,我们就可以使用它,具体如下。

@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

}

注意:如果想在javadoc中显示@ClassPreamble的信息,必须在定义ClassPreamble前面加上一句@Documented,并且导入annotation package,具体如下:

import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
   
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容