@Repeatable 注解的基本语法
注解通常只能直接修饰某个元素一次,如果修饰了多次那么会出现编译异常
public @interface Role {
String role() default "";
}
如果想要某个注解在某个元素上(直接)出现多次,那么就可以使用@Repeatable
注解
@Repeatable 有以下使用规则:
-
只能修饰注解。 【
@Target(ElementType.ANNOTATION_TYPE)
】 -
@Repeatable 注解存在一个value属性,表示包含可重复注解的注解类型 【
Class<? extends Annotation> value()
】 -
value 属性值表示的注解
必须存在value成员
且必须是数组
,这个value成员指定重复出现的注解类型
注意: 关于第3条这属于一种约定,具体原因,详情请看 ,getDeclaredAnnotationsByType 分析
demo
按照上面的规则,创建如下两个注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Roles {
//value属性必须存在,指定Role 属性可以重复存在
Role[] value();
}
@Repeatable(Roles.class)
public @interface Role {
String role() default "";
}
@Role(role = "role1")
@Role(role = "role2")
@Role(role = "role3")
public class Person {
// 省略一些方法属性
}
通过注解Role获取信息
这其实是间接存在的注解,可以通过下面的方法获取注解信息
@Test
public void indriectAnnotation(){
//间接存在
Arrays.asList(Person.class.getDeclaredAnnotationsByType(Role.class)).forEach(action-> {
if (action instanceof Role) {
System.out.println("getDeclaredAnnotationsByType\t"+ action.role());
}
});
//关联
Arrays.asList(Person.class.getAnnotationsByType(Role.class)).forEach(action-> {
if (action instanceof Role) {
System.out.println("getAnnotationsByType\t"+ action.role());
}
});
}
getDeclaredAnnotationsByType role1
getDeclaredAnnotationsByType role2
getDeclaredAnnotationsByType role3
getAnnotationsByType role1
getAnnotationsByType role2
getAnnotationsByType role3
当然除了上面的定义方式,还可以选择下面的方式:
@Roles({@Role(role="role1"),@Role(role="role2")})
public class Person{}
通过注解Roles获取信息
这中属于直接存在,可以通过下面的方法获取注解信息
@Test
public void directAnnotationRoles(){
Roles roleAnnotation = Person.class.getDeclaredAnnotation(Roles.class);
System.out.println("getDeclaredAnnotations ");
Arrays.stream(roleAnnotation.value()).forEach(role -> System.out.println(role.value()));
//存在(直接存在,继承直接存在)
Arrays.asList(Person.class.getAnnotations()).forEach(action -> {
if (action instanceof Roles) {
System.out.println("getAnnotations " );
Arrays.stream(roleAnnotation.value()).forEach(role -> System.out.println(role.value()));
}
});
// 直接存在 或间接存在
Arrays.asList(Person.class.getDeclaredAnnotationsByType(Roles.class)).forEach(action -> {
System.out.println("getDeclaredAnnotationsByType");
Arrays.stream(action.value()).forEach(role -> System.out.println(role.value()));
});
//关联
Arrays.asList(Person.class.getAnnotationsByType(Roles.class)).forEach(action -> {
if (action instanceof Roles) {
System.out.println("getAnnotationsByType");
Arrays.stream(roleAnnotation.value()).forEach(role -> System.out.println(role.value()));
}
});
}
getDeclaredAnnotations
role1
role2
getAnnotations
role1
role2
getDeclaredAnnotationsByType
role1
role2
getAnnotationsByType
role1
role2