How to Find All the Classes of a Package in Java
In this article let's take a look at how to find all classes of a package in Java
Join the DZone community and get the full member experience.Join For Free
To find all classes of a package in Java we can use the ClassHunter of Burningwave Core library. So we start by adding the following dependency to our pom.xml:
The next steps are the following:
- retrieving the ClassHunter through the ComponentContainer
- defining a regular expression that we must pass to the ClassCriteria object that will be injected into the SearchConfig object
- calling the loadInCache method that loads in the cache all loadable classes of the indicated paths, then applies the criteria filter and then returns the SearchResult object which contains the classes that match the criteria
And now let’s find all classes whose package contains “springframework” string:
In the example above the search is performed, as default, in all the runtime class paths but, if we want to search only in some jar of the runtime class paths or in other jar outside the runtime class paths we can expressly indicate them:
Let’s break down the example above:
- In the forPaths method we can add all absolute paths we want: both folders, zip, jar, ear, war and jmod files will be recursively scanned and in this case we are scanning only jar whose name contains the string spring
- 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 of the loaded paths even by simply calling the findBy method.
In this article we have learned an alternative way to find classes for a given criterion that we can change in any way according to our needs and the complete source code is available on GitHub.
Opinions expressed by DZone contributors are their own.