Java Annotation

[b]一) annotation的作用[/b]
annotation之于程序代码的作用大致可以归结为以下三点:
1) 给编译器(compiler)提供辅助信息,加强纠错和错误处理。比如注解override的函数是否符合override标准,某些warning是否抑制不抛等等。
2) 给某些软件提供信息,以生成相应的代码、xml文件或其它文档等相关内容。比如 Javadoc-generated。
3) 监控程序运行。比如对not null状态的监控。

[b]二) annotation的基本语法[/b]
annotation的语法很简单。以@开头,括号内依次写入元素及其值。一般来说annotation在声明classes, fields, methods时使用。

@Author(
name = "Benjamin Franklin",
date = "3/27/2003"
)
class MyClass() { ... }


而在Java SE 8中,annotation的使用场景做了进一步的扩展:

//Class instance creation expresson:
new @Interned MyObject();

//Type cast:
myString = (@NonNull String) str;

//implements clause:
class UnmodifiableList<T> implements
@Readonly List<@Readonly T> { ... }

//Thrown exception declaration:
void monitorTemperature() throws
@Critical TemperatureException { ... }

[b]三) annotation的分类[/b]
annotation的分类其实也很简单。就分为两类:自定义注解和预定义注解。
[b] 1)自定义注解:[/b]
我们可以像这样声明一个叫ClassPreamble的注解

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

声明完以后我们可以这样来使用它:

@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并没有什么特别之处,就像一段普通的注释一般。但与普通注释不同的是,我们可以使编译器根据ClassPremble注解,在生成说明文档时自动加入ClassPremble内声明的相关元素的信息(author、date等)。为此我们在声明时需要加上一个“@Document”:

@Documented
@interface ClassPreamble {

// Annotation element definitions

}

当然,如果我们需要在工程中广泛使用此类注解时,我们也可以考虑使用一下第三方提供的注解架包( Checker Framework就是其中之一)。它会提供给你很多有用的注解噢~~
[b]2) 预定义注解[/b]
顾名思义。JDK在发布时除了支持注解功能,也已经预先定义好了一部分非常常用的注解。具体有:
[b]@Deprecated:[/b]表明此类、方法或变量不建议使用。如果使用,将会抛出一个warning
[b]@override:[/b] 表明此方法是重载.如果不是,抛出error
[b]@SuppressWarnings:[/b] 忽略warning。也可以忽略指定类型的warning,比如:@SuppressWarnings("deprecation")
[b]@SafeVarargs:[/b] 忽略方法或构造函数入参的不安全操作问题。
[b]@FunctionalInterface:[/b]表明此是功能接口。
此外还有供注解使用的注解:
@Retention、@Documented、@Target、@Inherited、@Repeatable。这些注解也都不难理解,这里就不一一解释了。感觉需要注意的是@Repeatable,使用它时注解的声明步骤会多一步,即需要包含一个元素数组。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值