13

如何动态加载 jar 文件并列出其中的类?

4

5 回答 5

15

这是在 jar 中列出类的代码:

import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarList {
    public static void main(String args[]) throws IOException {

        if (args.length > 0) {
            JarFile jarFile = new JarFile(args[0]);
            Enumeration allEntries = jarFile.entries();
            while (allEntries.hasMoreElements()) {
                JarEntry entry = (JarEntry) allEntries.nextElement();
                String name = entry.getName();
                System.out.println(name);
            }
        }
    }
}
于 2010-08-07T06:14:31.053 回答
13

您可以使用以下命令从命令提示符查看 JAR 文件的内容:

jar tf jar-file

例如:

jar tf TicTacToe.jar


META-INF/MANIFEST.MF  
TicTacToe.class  
audio/  
audio/beep.au  
audio/ding.au  
audio/return.au  
audio/yahoo1.au  
audio/yahoo2.au  
images/  
images/cross.gif  
images/not.gif  
于 2015-02-19T12:58:02.477 回答
8

看看包中的类java.util.jar。您可以在网上找到有关如何列出 JAR 中的文件的示例,这里有一个示例。(另请注意该页面底部的链接,还有更多示例向您展示如何使用 JAR 文件)。

于 2010-08-07T05:50:38.107 回答
4

快速方法:只需将 .jar 作为 .zip 打开,例如在 7-Zip 中,然后查找目录名称。

于 2013-06-09T19:07:51.040 回答
0

这是一个扫描给定 jar 以查找扩展特定类的所有非抽象类的版本:

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.

于 2019-07-11T17:23:06.860 回答