- 论坛徽章:
- 0
|
[1]
http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
为什么要使用annotation?
首先要问这个问题:
需要知道annocation的 Retention Policy,分为三种:
SOURCE Annocations 存在于源文件,在编译时,被编译器忽略。这种annocation通常就替代传统的注释,目的是使注释更规范,和被专用的工具所读取和修改。比如,常见的注明版本号,作者,创建时间,bugfix情况等等。这里不举例了,参考[1]。
CLASS Annocations 存在于二进制的class中,而运行时被忽略。编译的时候会感知。
@Deprecated,@Override,@SuppressWarnings
已经比如说@Deprecated, 就是告诉编译器,这个方法已经过期了,不能够被使用,如果使用的话,在变异的时候要报错。
参考[1]
RUNTIME Annocation 运行时被感知。
例如下面的例子:import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface BugsFixed{
String[] value();
}。。。。@BugsFixed( { "457605", "532456"} )
class Foo { /* ... */ }
..... the code
Class cls = Foo.class;
BugsFixed bugsFixed =
(BugsFixed) cls.getAnnotation(BugsFixed.class);
String[] bugIds = bugsFixed.value();
for (String id : bugIds)
System.out.println(id);
would print
457605
532456 缺省的retention policy是CLASS
限制Annocation的应用范围CONSTRUCTOR, METHOD, FIELD, LOCAL_VARIABLE, PARAMETER, PACKAGE, and TYPE例如:@Target(ElementType.TYPE)
@interface ClassInfo {
String created();
String createdBy();
String lastModified();
String lastModifiedBy();
Revision revision();
}
如果将该ananocation使用与变量上,在编译的时候会报错。
学习到java persistencd api里的时候,大量用到annocation,我猜测,这些annocation会被运行时的容器所感知,以实现一些固定模式的操作,简化编程。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/10296/showart_361302.html |
|