This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: What is the best way to scan Java annotations at run time and search the entire classpath for annotated classes?

I’m working on a library that I want to allow users to annotate their classes, so when the Web application starts up, I need to scan the entire classpath for some annotations.

Do you know any libraries or Java tools that do this?

Edit: I’m thinking of new features like Java EE 5 Web services or EJB. You use @WebService or annotate classes that the @EJB system finds when it loads, so it can access them remotely.

Answer 1: the API

Component provider that scans the classpath from the base package. It then applies the exclusion and include filter to the result class to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
    System.out.println(bd.getBeanClassName());
Copy the code

Answer 2:

You can use ClassGraph to find classes with any given annotation, as well as to search for other criteria of interest, such as classes that implement a given interface. (Disclaimer, I’m the author of ClassGraph.) ClassGraph can build an abstract representation of all class graphs in memory (all classes, annotations, methods, method parameters, and fields), or classes in a whitelisted software package, all classes on or within the classpath.

You can query the class diagram as required. ClassGraph supports more classpath specification mechanisms and classloaders than any other scanner, and works seamlessly with the new JPMS module system, so if your code is based on ClassGraph, your code will have maximum portability.

See the API here.