Listing classes in a jar file

前端 未结 5 985
感动是毒
感动是毒 2021-02-14 01:20

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

5条回答
  •  长情又很酷
    2021-02-14 02:18

    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 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.

提交回复
热议问题