Listing classes in a jar file

Viewed 25358

How can I dynamically load a jar file and list classes which is in it?

5 Answers

Here is a version that scans a given jar for all non-abstract classes extending a particular class:

try (JarFile jf = new JarFile("/path/to/file.jar")) {
    for (Enumeration<JarEntry> en = jf.entries(); en.hasMoreElements(); ) {
        JarEntry e = en.nextElement();
        String name = e.getName();
        // Check for package or sub-package (you can change the test for *exact* package here)
        if (name.startsWith("my/specific/package/") && name.endsWith(".class")) {
            // Strip out ".class" and reformat path to package name
            String javaName = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
            System.out.print("Checking "+javaName+" ... ");
            Class<?> cls;
            try {
                cls = Class.forName(javaName);
            } catch (ClassNotFoundException ex)  { // E.g. internal classes, ...
                continue;
            }
            if ((cls.getModifiers() & Modifier.ABSTRACT) != 0) { // Only instanciable classes
                System.out.println("(abstract)");
                continue;
            }
            if (!TheSuper.class.isAssignableFrom(cls)) { // Only subclasses of "TheSuper" class
                System.out.println("(not TheSuper)");
                continue;
            }
            // Found!
            System.out.println("OK");
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

You can use that code directly when you know where are your jars. To get that information, refer to this other question, as going through classpath has changed since Java 9 and the introduction of modules.

Related