注解可以重复定义多个
@MyAnnotation()
@MyAnnotation(value="123")
class Person{
private String name;
private int age;
这就叫重复注解,但这么做报错了
jdk8之前的方式,要用数组来实现重复注解
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {
String value() default "hello";
}
public @interface MyAnnotations {
MyAnnotation[] value();
}
//@MyAnnotation(value="hi")
//@MyAnnotation(value="abc")
@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="abc")})
class Person{
private String name;
private int age;
public Person() {
}
可重复注解的实现步骤:
1.在MyAnnotation上去声明@Repeatable(MyAnnotations.class),成员值为MyAnnotations.class
让这两个注解关联在一起
2.MyAnnotation的Target和Retention和MyAnnotations相同
3.且要么都有@Inherited修饰,要么都没有这个东西修饰,否则运行出错
两者的元注解需要是相同的
@Repeatable(MyAnnotations.class)//MyAnnotation和MyAnnotations的生命周期要一致,否则报错,两者的修饰结构也要相同,所以要用相同的Target
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {
String value() default "hello";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {
MyAnnotation[] value();
}
@MyAnnotation(value="hi")
@MyAnnotation(value="abc")
class Person{
private String name;
private int age;
public Person() {
}