spring-core:注解扫描工具MergedAnnotations获取复合注解上的元注解

上一篇博客《sping-core:注解扫描工具AnnotatedElementUtils.hasMetaAnnotationTypes方法说明》介绍了通过AnnotatedElementUtils.hasMetaAnnotationTypes方法判断指定的AnnotatedElement对象(Class,Method,Field)是否是否用复合注解类型进行注解,而该复合注解是用annotationType指定的注解作元注解的。
那么既然能判断是否存在元注解,能不能获取元注解对象呢?
AnnotatedElementUtils也提供了静态方法getMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType)但它返回的是元注解的类名集合Set<String>

如何获取元注解对象呢?AnnotatedElementUtils并没有提供这个方法,但是参照getMetaAnnotationTypes(AnnotatedElement element, Class<? extends Annotation> annotationType)也能自己实现:

示例如下:

	/**
	 * 返回element指定对象上所有annotationType指定类型的元注解集合
	 * @param <A>
	 * @param element
	 * @param annotationType
	 */
	public static <A extends Annotation> Set<A>  getMetaAnnotations(AnnotatedElement element,Class<A> annotationType) {
		MergedAnnotations mergedAnnotations = MergedAnnotations.from(element, 
			SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none());
		return mergedAnnotations.stream(annotationType)
			.filter(MergedAnnotation::isMetaPresent)
			.map(MergedAnnotation::synthesize)
			.collect(Collectors.toSet());
	}

示例:
元注解 @CellLogTag

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD})
public @interface CellLogTag {
}

使用 @CellLogTag的作元注解的复合注解 @TestLogTag

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@CellLogTag
public @interface TestLogTag {
}

调用示例:

	@Test
	public void test8GetMetaAnnotationTypes() {
		try {
			{
				Method method = ClassB.class.getMethod("m0");
				Set<CellLogTag> metaAnnots = getMetaAnnotations(method,CellLogTag.class);
				assertTrue(!metaAnnots.isEmpty());
				log("{}",metaAnnots);
			}
		} catch (Throwable e) {
			e.printStackTrace();
			fail();
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值