DEV Community

loading...
Cover image for How to find all the classes of a package in Java

How to find all the classes of a package in Java

Burningwave
Burningwave is a set consisting of a Java frameworks building library and other applications and frameworks based on it
Updated on ・2 min read

To find all classes of a package in Java we need to use the ClassHunter 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 (optionally) passed the paths to be scanned and the query criteria represented by the ClassCriteria. If no path will be passed to SearchConfig, the scan will be executed on the paths indicated by the ‘paths.hunters.default-search-config.paths’ property of the burningwave.properties.

The fastest and most optimized way to find all the classes of a package is by iterating the resources accessible through ClassLoader thus avoiding that ClassLoader loads the classes that are outside the scanned paths:

The loadInCache method loads all classes in the paths of the SearchConfig received as input and then execute the queries of the ClassCriteria on the cached data. Once the data has been cached, it is possible to take advantage of faster searches for the loaded paths also through the findBy method. 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. It is possible to clear the cache individually for every hunter (ClassHunter, ByteCodeHunter and ClassPathHunter) with clearCache method but to avoid inconsistencies it is recommended to perform this cleaning using the clearHuntersCache method of the ComponentSupplier. To perform searches that do not use the cache you must instantiate the search configuration with SearchConfig.withoutUsingCache method.

Finding all classes that have package name that matches a regex

Finding all annotated classes of a package without considering the classes hierarchy

Finding all annotated classes of a package by considering the classes hierarchy

Finding all classes of a package that have a particular annotation on at least one Field without considering the classes hierarchy

Finding all classes of a package that have a particular annotation on at least one Field by considering the classes hierarchy

In this article we learned how to find all classes within a package and the complete code of the example above is available here.

Discussion (0)