自定义一个Annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
public @interface MyAnnotation {
/**
* 姓名
*
* @return
*/
String name() default "张三";
/**
* 年龄
*
* @return
*/
int age();
/**
* 爱好
*
* @return
*/
String[] hobby() default { "打篮球", "踢足球" };
}
获取Annotation内的信息
import java.lang.annotation.Annotation;
public class A {
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, ClassNotFoundException {
Annotation[] arr = null;
arr = Class.forName("B").getMethod("man").getAnnotations();
for (Annotation a : arr) {
System.out.println(a);
if (a instanceof MyAnnotation) {
System.out.println("姓名:" + ((MyAnnotation) a).name());
System.out.println("年龄:" + ((MyAnnotation) a).age());
for (String str : ((MyAnnotation) a).hobby()) {
System.out.println("爱好:" + str);
}
}
}
}
}
class B {
@MyAnnotation(age = 20)
public void man() {
}
}