1

How can I get the Class objects for all the classes in the module java.base programmatically? I'm open to using any external libraries. I have looked at the Reflections library but could not get a list of classes in the built-in Java Library, only classes on the classpath. I tried to manually do this by iterating through all the files in my file system, but (as far as I'm aware) I cannot get to the classes because they are inside a jar file. What would the code look like for getting all the Class objects for the classes in java.base?

Thanks.

Sam Hooper
  • 187
  • 8
  • Maybe this: [Can you find all classes in a package using reflection?](https://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection) – akuzminykh Sep 19 '20 at 19:58

1 Answers1

0

I was able to extract all of the classes from the src.zip file:

public class TypeUtils {
    private static Set<Class<?>> classes;
    private static final Set<String> CONSIDERED_MODULES = Set.of("java.base");
    public static void main(String[] args) {
        try {
            findClasses();
            classes.forEach(System.out::println);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void findClasses() throws IOException {
        classes = new HashSet<>();
        File root = new File(System.getProperty("java.home"));
        File lib = new File(root, "lib");
        ZipFile srczip = new ZipFile(new File(lib, "src.zip"));
        Iterator<? extends ZipEntry> itr = srczip.entries().asIterator();
        while(itr.hasNext())
            extractFromEntry(itr.next());
    }
    
    private static void extractFromEntry(ZipEntry entry) {
        String name = entry.getName();
        if(name.endsWith(".java")) {
            int firstSlash = name.indexOf('/');
            String moduleName = name.substring(0, firstSlash);
            if(!CONSIDERED_MODULES.contains(moduleName)) return;
            String fullyQualifiedName = name.substring(firstSlash + 1, name.length() - 5).replace('/', '.');
            if(fullyQualifiedName.endsWith("-info")) return; //catches module-info or package-info files
            try {
                Class<?> clazz = Class.forName(fullyQualifiedName);
                classes.add(clazz);
            }
            catch (ClassNotFoundException e) {}
        }
    }
}
Sam Hooper
  • 187
  • 8