简体   繁体   English

Java 运行时相当于使用 javax Processor / google @AutoService 进行注释处理

[英]Java runtime equivalent to annotation processing with javax Processor / google @AutoService

I have worked with annotation processing on RetentionPolicy.SOURCE level, using javax.annotation.processing.Processor/AbstractProcessor and com.google.auto.service.@AutoService before, that's when I first discovered the very helpful RoundEnvironment.getElementsAnnotatedWith() .我之前曾使用javax.annotation.processing.Processor/AbstractProcessorcom.google.auto.service.@AutoServiceRetentionPolicy.SOURCE级别进行注释处理,那是我第一次发现非常有用的RoundEnvironment.getElementsAnnotatedWith()的时候。

Now, in a completely unrelated project, I need the same functionality, but at runtime.现在,在一个完全不相关的项目中,我需要相同的功能,但在运行时。 In other words, I have the Annotation换句话说,我有注释

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapper {
    Class<?> forUID() default Object.class;
}

and I want to obtain every single element (of course it can only be constructors or methods) anntotated with @Mapper .我想获得用@Mapper的每一个元素(当然它只能是构造函数或方法)。 Can I use RoundEnvironment at runtime?我可以在运行时使用RoundEnvironment吗? If yes, how do I obtain an instance of it?如果是,我如何获得它的实例? If no, is there a runtime equivalent to it?如果没有,是否有与之等效的运行时? Thanks in advance.提前致谢。

Using:使用:

  • JDK 11 (openjdk11) JDK 11 (openjdk11)
  • Maven 3.6.3 Maven 3.6.3

Annotation processing is a compile time only tool, the retention on the annotation is just saying if the annotation will be available at runtime or just in source, for run time you can use reflection, but also you still can use annotation processor at compile time to generate a class that list all the types annotated with a specific annotation.注释处理是仅编译时的工具,注释上的保留只是说明注释是否在运行时可用或仅在源代码中可用,对于运行时您可以使用反射,但您仍然可以在编译时使用注释处理器来生成一个 class 列出使用特定注释注释的所有类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM