Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解
public class AnnotationTest {
//可重复的注解
@MyAnnotation("hello")
@MyAnnotation("word")
public void show(@MyAnnotation("abc") String str){//可用于类型的注解
}
@Test
public void test1() throws NoSuchMethodException {
Class<AnnotationTest> clazz = AnnotationTest.class;
Method m1 = clazz.getMethod("show");
MyAnnotation[] ma = m1.getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation m :ma) {
System.out.println(m.value());
}
//hello
//word
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,TYPE_PARAMETER})
public @interface MyAnnotations {
MyAnnotation[] value();
}
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,TYPE_PARAMETER})
public @interface MyAnnotation {
String value() default "hi";
}