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

How to build a list of classes annotated with my custom annotation?(如何构建使用我的自定义注释注释的类列表?)
本文介绍了如何构建使用我的自定义注释注释的类列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想获取应用程序中使用 @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.

这篇关于如何构建使用我的自定义注释注释的类列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)