Annotations 注释基础_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Annotations 注释基础

Annotations 注释基础

 2014/3/26 12:59:36  cucaracha  程序员俱乐部  我要评论(0)
  • 摘要:很多Annotation都是为了取代代码中传统的注释。例如,假设你编写的代码中有下面这段注释:publicclassGeneration3ListextendsGeneration2List{//Author:JohnDoe//Date:3/17/2002//Currentrevision:6//Lastmodified:4/12/2004//By:JaneDoe//Reviewers:Alice,Bill,Cindy//classcodegoeshere
  • 标签:not Annotation 注释
很多 Annotation 都是为了取代代码中传统的注释

例如,假设你编写的代码中有下面这段注释:
class="java" name="code">
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 来取代传统的注释,首先需要定义一个 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 类型的语法看起来很像定义接口的语法,不过在 interface 关键字前面加了一个 @ 符号。
在上面这个例子中还定义了 Annotation 的元素,定义元素的语法看起来很像定义方法的语法,每个元素都可以使用 default 关键字来定义默认值。

上面的 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

}


注意:如果要让 @ClassPreamble 出现在 Javadoc-generated 生成的文档中,那么需要给它加上 @Documented 注释:
// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
   
}


文章来源:http://www.aptusource.org/2014/03/annotations-base/
发表评论
用户名: 匿名