Java注释——采用metadata机制,对某点程序代码作解释说明,将程序的元素如:类,方法,属性,参数,本地变量,包和元数据联系起来。这样编译器可以将元数据存储在class文件中。这样虚拟机和其它对象可以根据这些元数据来决定如何使用这些程序元素或改变它们的行为。
事先定义好的三种annotation类型,都位于java.lang包里:
1 Override 用来指示一个方法,它覆盖了它的基类的方法
2 Deprecated 指出某一个方法或是元素类型的使用时被阻止的
3 SupressWarnings 会关掉class、method、field与variable初始化的编译器警告
我们可以创建自定义的annotation类型,很类似于声明一个接口:
public @interface TODO {
String value();
}
编译器自动使用相同名称创建了一个成员变量value,使用时可以这么写:
@TODO(value="Finish homework")
Java提供了四种基本的meta-annotation如下,都位于java.lang.annotation包里:
1 Target 指定哪个程序单元可以有其所定义的annotation
参数类型是ElementType[],其中ElementType定义为如下枚举
public enum ElementType {
TYPE, // Class, interface, or enum (but not annotation)
FIELD, // Field (including enumerated values)
METHOD, // Method (does not include constructors)
PARAMETER, // Method parameter
CONSTRUCTOR, // Constructor
LOCAL_VARIABLE, // Local variable or catch clause
ANNOTATION_TYPE, // Annotation Types (meta-annotations)
PACKAGE // Java package
}
不使用时所有程序单元都适用
2 Retention 指出是否编译器要丢掉一个annotation,或者是否将一个annotation保存在class文件里
参数是RetentionPolicy类型,定义如下
public enum RetentionPolicy {
SOURCE, // Annotation is discarded by the compiler
CLASS, // Annotation is stored in the class file, but ignored by the VM
RUNTIME // Annotation is stored in the class file and read by the VM
}
3 Documented 指出被定义的annotation应该被视为所注释的程序单元的公开API之一
4 Inherited 被应用于目标为class的annotation类型上,指出此被注释的类型是能够通过继承得到的
最后,来谈一下annotation的反射。java.lang.reflect包里的AnnotatedElement接口可以直接拿来访问被annotated的方法,具体的还是看例子吧~
posted on 2009-06-14 13:18
chenkkkabc 阅读(118)
评论(0) 编辑 收藏 所属分类:
java特性