当我们需要重复使用某个注解时,希望利用相同的注解来表现所有的形式时,我们可以借助@Repeatable注解。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Persons {
Person[] value();
}
@Repeatable(Persons.class)
public @interface Person{
String role() default "";
}
创建一个Man类,给Man类添加一些身份(加上多个Person注解)
@Person(role="CEO")
@Person(role="husband")
@Person(role="father")
@Person(role="son")
public class Man {
String name="";
}
主方法中访问该注解,获取关于Man类的Person注解的信息
public static void main(String[] args) {
Annotation[] annotations = Man.class.getAnnotations();
System.out.println(annotations.length);
Persons p1=(Persons) annotations[0];
for(Person t:p1.value()){
System.out.println(t.role());
}
}
运行结果:
1
CEO
husband
father
son
说明,虽然看似时获取了好几个注解,但是由于person和persons的关系,最终只获取了一个注解而已,这个注解其实已经将上面的n的注解,都保存了一遍,就是这点意思!!!