Java8引入的新特性,在需要对同一种注解多次使用时,往往需要借助@Repeatable。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Roles{
Role[] value() default {};
}
@Repeatable(Roles.class) //在同一个地方多次使用注解@Role,与在该地方使用Roles等效
@Retention(RetentionPolicy.RUNTIME)
@interface Role{
String value() default "";
}
@Role("student")
@Role("children")
class A{
}
@Roles({@Role("teacher"),@Role("adult")})
class B{
}
public class Test8 {
public static void main(String[] args){
System.out.print("类A:");
if (A.class.isAnnotationPresent(Roles.class)){
Roles roles=A.class.getAnnotation(Roles.class);
for (Role role:roles.value()){
System.out.print(role.value()+" ");
}
}
System.out.println();
System.out.print("类B:");
if (B.class.isAnnotationPresent(Roles.class)){
Roles roles=B.class.getAnnotation(Roles.class);
for (Role role:roles.value()){
System.out.print(role.value()+" ");
}
}
}
@Target是声明Persons注解的作用范围,参数ElementType.Type代表可以给一个类型进行注解,比如类,接口,枚举。
@Retention是注解的有效时间,RetentionPolicy.RUNTIME是指程序运行的时候。
@Repeatable括号内的就相当于用来保存该注解内容的容器。