How to build a list of classes annotated with my custom annotation?

后端 未结 8 1139
梦毁少年i
梦毁少年i 2020-12-23 16:52

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?

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 17:17

    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.

    This approach is implemented by libraries like Scannotation and Reflections.

    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.

    The above mechanism is implemented in ClassIndex library.

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

提交回复
热议问题