How to Scan the classpath in Java

Jim Jerald Burton
2 min readNov 25, 2021

--

In this article we will show how to scan the classpath in Java. Thanks to lambda expressions it is possible to dinamically inject algorithms into macro algorithms that iterate certain entities and execute the lambdas on the iterated entity: this is what happens with the ClassHunter component of Burningwave Core library.

The ClassHunter is a classpath scan engine that queries iterated classes and returns only the classes that match a chosen criteria, moreover the searches are executed in a multithread context and recursively through folder and supported compressed files (zip, jar, jmod, war and ear) even in nested compressed files. To use the ClassHunter you should simply add the following to your projects dependencies:

To perform a scan it is necessary to create a configuration object of type SearchConfig to which must be passed the paths to be scanned and the query criteria represented by the ClassCriteria. The ClassHunter can cache the classes found for classpath in order to perform the next searches faster.

So let’s take a look to the code by executing two different searches:

  • finding all classes that have a package name that matches a regular expression

The findBy method loads all classes in the paths of the SearchConfig received as input and then execute the queries of the ClassCriteria. The findBy method also caches data so after the first search it is possible to take advantage of faster searches. In addition to the loadCache method, loading data into the cache can also take place via the findBy method if the latter receives a SearchConfig without ClassCriteria as input.

  • finding all annotated classes

In the example above unlike the previous example:

  • we create a complex ClassCriteria with which we ask for all classes that have at least one annotation on class declaration or at least one annotation on the declaration of any of its members (fields, methods or constructors). Notice the call to the ‘byScanUpTo’ method: it receives a lambda expression as input through which, in this case, we ask the scanning engine to apply the filter of the criteria for member (ConstructorCriteria, FieldCriteria and MethodCriteria) only on the iterated class and not on its entire hierarchy because otherwise, by default, the filters injected in the member criterias, are applied to the entire hierarchy (see ‘ClassHunter: in depth look to and configuration guide’).

--

--