美文网首页
@AliasFor注解的实现之MergedAnnotations

@AliasFor注解的实现之MergedAnnotations

作者: engineer_tang | 来源:发表于2022-07-27 11:04 被阅读0次

MergedAnnotations接口的类图如下:


image.png

提供对合并注释集合的访问,这些注释通常从类或方法等源获取。
每个合并注释表示一个视图,其中属性值可以从不同的源值“合并”,通常:

  • 注释中一个或多个属性上声明的显式和隐式@AliasFor
  • 元注释声明的显式@AliasFor
  • 元注释的基于约定的属性别名
  • 来自元注释声明
    例如,@PostMapping注释可以定义如下:
 @Retention(RetentionPolicy.RUNTIME)
   @RequestMapping(method = RequestMethod.POST)
   public @interface PostMapping {
  
       @AliasFor(attribute = "path")
       String[] value() default {};
  
       @AliasFor(attribute = "value")
       String[] path() default {};
   }

如果一个方法用@PostMapping(“/home”)注释,它将包含@PostMapping和元注释@RequestMapping的合并注释。@RequestMapping注释的合并视图将包含以下属性:


image.png

MergedAnnotations 可从java AnnotatedElement中获得,它们也可以用于不使用反射的源(例如那些直接解析字节码的源)。可以使用不同的搜索策略来定位包含要聚合的注释的相关源元素。例如:MergedAnnotations.SearchStrategy.TYPE_HIERARCHY将搜索超类和实现的接口。
从MergedAnnotations实例中,您可以获得单个注释,也可以流式传输所有注释,或者只传输与特定类型匹配的注释。您还可以快速判断注释是否存在。

实例:

   // is an annotation present or meta-present?
   mergedAnnotations.isPresent(ExampleAnnotation.class);
  
   // get the merged "value" attribute of ExampleAnnotation (either directly or
   // meta-present)
   mergedAnnotations.get(ExampleAnnotation.class).getString("value");
  
   // get all meta-annotations but no directly present annotations
   mergedAnnotations.stream().filter(MergedAnnotation::isMetaPresent);
  
   // get all ExampleAnnotation declarations (including any meta-annotations) and
   // print the merged "value" attributes
   mergedAnnotations.stream(ExampleAnnotation.class)
       .map(mergedAnnotation -> mergedAnnotation.getString("value"))
       .forEach(System.out::println);

相关文章

网友评论

      本文标题:@AliasFor注解的实现之MergedAnnotations

      本文链接:https://www.haomeiwen.com/subject/txztwrtx.html