如何构建使用我的自定义注释注释的类列表?

2022-01-13 00:00:00 annotations java

我想获取应用程序中使用 @Custom 注释进行注释的类的完整列表.这种操作的最佳机制是什么?

I want to get a complete list of classes in the application which are annotated with @Custom annotation. What is the best mechanism for this operation?

ps.例如,JAX-RS 实现如何找到所有使用 @Path 注释的类?我想使用相同的机制.

ps. For example, how JAX-RS implementations find all classes that are annotated with @Path? I would like to use the same mechanism.

推荐答案

通常这是使用称为类路径扫描的过程完成的.一般来说,类加载器不允许扫描类路径上的所有类.但通常唯一使用的类加载器是 UrlClassLoader,我们可以从中检索目录和 jar 文件列表(参见 getURLs) 并一一打开以列出可用的类.

Usually this is done using the process called classpath scanning. In general class loaders do not allow for scanning through all the classes on the classpath. But usually the only used class loader is UrlClassLoader from which we can retrieve the list of directories and jar files (see getURLs) and open them one by one to list available classes.

这种方法由 Scannotation 和 反思.

另一种方法是使用 Java Pluggable注释处理 API 编写注释处理器,该处理器将在编译时收集所有带注释的类并构建索引文件以供运行时使用.

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use.

上述机制在ClassIndex库中实现.

使用类路径扫描通常比编译时索引慢两个数量级.请参阅此基准.

Using classpath scanning is usually two orders of magnitude slower than compile-time indexing. See this benchmark.

相关文章