Search code examples
javareflectionclasspathreflections

Reflections Library to Find All Classes within a Package


I am using the below code to find all of the Classes within a given package name. This works fine when the code is placed directly into my project. However, calling the service from a Commons Jar I put together isn't returning the data from my project. Can this be achieved? I am using org.reflection.Reflections library.

public Set<Class<?>> reflectPackage(String packageName){
    List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());

    Reflections reflections = new Reflections(
                              new ConfigurationBuilder().setScanners(
                              new SubTypesScanner(false), 
                              new ResourcesScanner()).setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(
                              new ClassLoader[0]))).filterInputsBy(
                              new FilterBuilder().include(FilterBuilder.prefix(packageName))));

    return reflections.getSubTypesOf(Object.class);
}

Project Structure 

Eclipse --- Security Base // Project
        |     |
        |     --- reflectPackage("com.app.controller") call
        |         // Note: this package is within this project, not the Commons project.
        | 
        --- Commons // Project
             |
             --- Reflector // Class
                 |
                 --- reflectPackage // Method

Solution

  • I have used Fast Classpath Scanner in one of our projects and found it really useful. It has a lot of useful functionalities when it comes to class path scanning. An example is shown below which will give information about classes inside a package. It will scan and find packages/classes even if they are part of a third party jar.

    public Set<Class<?>> reflectPackage(String packageName) {
        final Set<Class<?>> classes = new HashSet<>();
        new FastClasspathScanner("your.package.name")
           .matchAllClasses(new ClassMatchProcessor() {
    
            @Override
            public void processMatch(Class<?> klass) {
                classes.add(klass);
            }
        }).scan();
        return classes;
    }