Class.forName not working when using subproject

Hi all! I am using the following methods in a ClassFinder.java to load all classes in a package so the static initialization blocks of each class are executed:

public static Set<Class<?>> loadClassesInPackage(String packageName) {
        InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(packageName.replaceAll("[.]", "/"));
        assert stream != null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        return reader.lines().filter(line -> line.endsWith(".class")).map(line -> getClass(line, packageName)).collect(Collectors.toSet());
    }
private static Class<?> getClass(String className, String packageName) {
        try {
            return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.')));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not find class: " + packageName + "." + className);
        }
    }

This used to work, when my project was one big project (see below) where a Main.java calls a method in A.java, which then uses ClassFinder.java to load all static blocks of classes in package_to_load. Now that I’ve restructured (see below), everything compiles, but when the loading is executed, none of the static blocks are executed. Since it compiles and executes fine using the application plugin (except for the loading), I’m assuming that the build.gradle files and settings.gradle are set up correctly.

It seems that the classpath changes when using subprojects, does anyone have any ideas?

Original structure:

my_project/
└─ src/
   └─ main/
      └─ java/
         └─ main_package/
            ├─ sub_package/
            │  ├─ sub_sub_package/
            │  │  ├─ package_to_load/
            │  │  └─ A.java
            │  └─ ClassFinder.java
            └─ Main.java

New structure:

my_project/
├─ sub_project/
│  └─ src/
│     └─ main/
│        └─ java/
│           └─ sub_project_package/
│              ├─ sub_sub_package/
│              │  ├─ package_to_load/
│              │  └─ A.java
│              └─ ClassFinder.java
└─ src/
   └─ main/
      └─ java/
         └─ main_package/
            └─ Main.java

It likely stopped working because the subproject dependency relationship is now including jar files on the classpath instead of a directory of class files.

There are libraries out there that can probably help you, for example java - Can you find all classes in a package using reflection? - Stack Overflow

Is there any way to traverse these jars or embed the class files instead?

Sadly, using reflections (or any library except for the standard library for that matter) is disallowed by my Professor. Is there any way to print the “paths” inside the jar, or access them through the jar wrapper?