Annotations 注释基础

很多 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 来取代传统的注释,首先需要定义一个 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

}


文章来源:[url]http://www.aptusource.org/2014/03/annotations-base/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值