Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

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

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. For example, how JAX-RS implementations find all classes that are annotated with @Path? I would like to use the same mechanism.

question from:https://stackoverflow.com/questions/4107498/how-to-build-a-list-of-classes-annotated-with-my-custom-annotation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...