Finding All Classes with ClassPath Provided by the Java Guava Library
This page explains how to find classes included in a package by using ClassPath from the Guava library.
Finding all loadable classes
Here, we will look at how to find classes by using the Google Guava library.
Google Guava provides the ClassPath utility class, which scans class loader sources and finds all loadable classes.
The example below finds and displays all classes under the package received as input.
package com.devkuma.guava.classloader;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.reflect.ClassPath;
public class FindAllClasses {
public Set<Class> findAllClasses(String packageName) throws IOException {
return ClassPath.from(ClassLoader.getSystemClassLoader())
.getAllClasses()
.stream()
.filter(clazz -> clazz.getPackageName()
.startsWith(packageName))
.map(clazz -> clazz.load())
.collect(Collectors.toSet());
}
public static void main(String[] args) throws IOException {
FindAllClasses instance = new FindAllClasses();
Set<Class> classes = instance.findAllClasses("com.devkuma.guava");
for (Class clazz : classes) {
System.out.println(clazz.getCanonicalName());
}
}
}
Execution result:
com.devkuma.guava.joiner.JoinerWithKeyValueSeparator
com.devkuma.guava.joiner.JoinerArrayJoin
com.devkuma.guava.strings.StringCommonPrefixCommonSuffix
com.devkuma.guava.joiner.JoinerListJoin
... omitted ...
The package name entered was com.devkuma.guava.