Skip to content

Can you find all classes in a package using reflection?

Yes, it is possible to find all classes in a package using reflection in Java. You can use the ClassLoader.getSystemClassLoader() method to get the system class loader and then use the getResource method to locate the package directory. Here is an example of how you can do this:

Note: This approach only works when the code is running from a file system directory. It will fail if the application is packaged in a JAR file or runs under the Java Platform Module System (JPMS). For production environments, consider using ServiceLoader or a framework-specific scanner like Spring's ClassPathScanningCandidateComponentProvider.


java
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class ClassScanner {
    public static void main(String[] args) {
        String packageName = "com.example.mypackage";
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        URL packageURL = classLoader.getResource(packageName.replace('.', '/'));

        if (packageURL != null) {
            try {
                List<Class<?>> classes = new ArrayList<>();
                scanPackage(new File(packageURL.toURI()), packageName, classes);
                // do something with the classes
            } catch (IOException | URISyntaxException e) {
                throw new RuntimeException("Failed to scan package", e);
            }
        }
    }

    private static void scanPackage(File dir, String packageName, List<Class<?>> classes) throws IOException {
        if (!dir.exists() || !dir.isDirectory()) return;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    scanPackage(file, packageName + "." + file.getName(), classes);
                } else if (file.isFile() && file.getName().endsWith(".class")) {
                    String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6);
                    try {
                        classes.add(Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        // Ignore invalid class names
                    }
                }
            }
        }
    }
}

This code will find all the classes in the package com.example.mypackage and load them using the system class loader. You can then do something with the classes, such as calling a method or instantiating an object.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.