重复注解
- 重复注解表示可以在同一处位置(方法,类,类变量等等)多次使用同一个注解,效果如下.
public class TestJava8_12 {
@MyAnnotation("xiemaoshu11111111111")
@MyAnnotation("lanChaoGou")
public void show() {
System.out.println("xiemaoshu");
}
}
如何定义重复注解
- 定义重复注解需要在原有的注解基础上添加 @Repeatable 这个元注解标签.
- 定义重复注解需要两个类,一个是注解类,一个是注解的容器类
- 注解类—MyAnnotation
- 注解类中使用@Repeatable 声明注解的容器类型为 MyAnnotationContainer.class
@Repeatable(MyAnnotationContainer.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
String value() default "xiemaoshu";
}
- 注解容器类—MyAnnotationContainer
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotationContainer {
MyAnnotation[] value();
}
类型注解
- 在注解类中的@Target 元注解中添加变量"TYPE_PARAMETER" 可以使得注解能够定义在类型上
@Repeatable(MyAnnotationContainer.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER})
@Retention(RetentionPolicy.SOURCE)
public @interface MyAnnotation {
String value() default "xiemaoshu";
}
public void test1( @MyAnnotation("xiemaoshu") String string) {
}