Java 8 可重复注解与类型注解
Java 8 对注解处理提供了两点改进:可重复的注解及可用于类型的注解。
// 首先要提供一个容器,MyAnnotation 才能用于可重复注解
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {
MyAnnotation[] value();
}
@Repeatable(MyAnnotations.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
注解具体使用如下:
@Test
public void test() throws NoSuchMethodException {
Class<AnnotationTest> clazz = AnnotationTest.class;
Method method = clazz.getMethod("show", String.class);
MyAnnotation[] ans = method.getAnnotationsByType(MyAnnotation.class);
for (MyAnnotation an : ans) {
System.out.println(an.value());
}
}
@MyAnnotation("hello")
@MyAnnotation("world")
public void show(@MyAnnotation("param") String s) {
}