Annotation是一种提供元数据描述的机制,可以为类、字段、方法、参数等程序元素添加元数据信息。Annotation能够在编译时进行处理,也可以在运行时通过Java反射机制获取它们的信息。
下面是一个Java SE中使用Annotation的示例:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String name();
int age() default 20;
String[] hobbies();
}
这个例子中,MyAnnotation是一个注解,它被定义为@Retention(RetentionPolicy.RUNTIME)和@Target(ElementType.METHOD),表示它在运行时依然存在,作用于方法上。该注解包含三个元素,分别为name、age和hobbies,其中age元素有一个默认值20。
以下是一个如何在方法上使用MyAnnotation的例子:
public class MyClass {
@MyAnnotation(name = "John Smith", hobbies = {
"reading", "writing"})
public void myMethod() {
// 方法体
}
}
在这个例子中,我们为myMethod方法添加了MyAnnotation,为其添加了name和hobbies两个元素的值。根据上面的定义,age元素使用了默认值20。
我们可以使用反射机制获取MyAnnotation注解中的元素值,例如:
public class AnnotationDemo {
public static void main(String[] args) throws Exception {
MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("name: " + annotation.name());
System.out.println("age: " + annotation.age());
System.out.println("hobbies: ");
for (String hobby : annotation.hobbies()) {
System.out.println(hobby);
}
}
}
这个例子通过反射机制获取了myMethod方法上的MyAnnotation注解,并输出了所有的元素值。
运行上述代码,将会得到以下输出结果:
name: John Smith
age: 20
hobbies:
reading
writing