在Java 程序中,除了源程序之外,我们还会用到Javadoc 标签对类、方法或成员变量进行注释。JDK5.0 的注解可以看成是Javadoc 标签和Xdoclet 标签的延伸和发展。在JDK5.0 中我们可以自定义标签,并通过Java语言的反射机制获取类中标注的注解。
@Retention(RetentionPolicy.RUNTIME) // 声明注解的保留期限
@Target(ElementType.METHOD) // 可使用注解的目标类型
public @interface AnnoTest { // 定义注解
boolean value() default true; // 声明注解成员
}
public class UseAnnotation {
@AnnoTest(value = true)
public void method1(String name) {
System.out.println("method1 " + name);
}
@AnnoTest(value = false)
public void method2(String name) {
System.out.println("method2 " + name);
}
}
public class AnnoClient {
public static void main(String[] args) {
Class<UseAnnotation> clazz = UseAnnotation.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
AnnoTest at = method.getAnnotation(AnnoTest.class);
if (at != null) {
if (at.value()) {
System.out.println(method.getName() + " need test.");
} else {
System.out.println(method.getName() + " do not need test.");
}
}
}
}
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE
}