元数据会给源代码添加一些辅助信息。这个辅助信息叫注释,annotation,它不会改变程序的运行。这种元数据可以为其它一些工具所使用,比如代码生成器,使其能够在运行的时候生成附加代码。依赖注入框架,像Spring,也会用到注释。注释可以附着在类或方法上。关键字interface前面加上@就能创建注释了。
package org.kodejava.example.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnno {
String value();
String greetTo();
}
package org.kodejava.example.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@HelloAnno(value = "Hello", greetTo = "Universe")
public class GettingAnnotation {
public static void main(String[] args) {
GettingAnnotation demo = new GettingAnnotation();
Class clazz = demo.getClass();
Annotation[] annotations = clazz.getAnnotations();
for (Annotation anno : annotations) {
System.out.println("Annotation Type: " + anno.annotationType());
}
HelloAnno anno = (HelloAnno) clazz.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
try {
Method m = clazz.getMethod("sayHi");
anno = m.getAnnotation(HelloAnno.class);
System.out.println("Anno Value : " + anno.value());
System.out.println("Anno GreetTo: " + anno.greetTo());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
demo.sayHello();
}
@HelloAnno(value = "Hi", greetTo = "Alice")
public void sayHi() {
}
@HelloAnno(value = "Hello", greetTo = "Bob")
public void sayHello() {
try {
Method m = getClass().getMethod("sayHello");
HelloAnno anno = m.getAnnotation(HelloAnno.class);
System.out.println(anno.value() + " " + anno.greetTo());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
原文: http://www.kodejava.org/examples/501.html