问题 如何从Java获取jar文件的主类名?


我想使用URLClassLoader加载并执行外部jar文件。

从中获取“Main-Class”的最简单方法是什么?


4118
2017-12-16 12:06


起源

我不确定你正在寻找什么,但是如果jar正确组合,你会发现jar中有一个清单文件,它指定哪个是主类。因此,你不需要弄明白。 - hovanessyan
我正在寻找简单的方法,无需手动读取该文件。是否 java -jar 使用一些库函数从manifest中读取属性? - Vi.
我不知道,情况很可能就是这样。官方文档只是说:在清单中设置Main-Class标头后,然后使用以下形式的java命令运行JAR文件:java -jar JAR-name Main中指定的类的主要方法执行类头。如果您可以在该jar中强制执行清单,那么这将是最简单的(也可能是更好的)方式。 - hovanessyan


答案:


这里 - 列出jarfile的主要属性

import java.util.*;
import java.util.jar.*;
import java.io.*;

public class MainJarAtr{
    public static void main(String[] args){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.print("Enter jar file name: ");
            String filename = in.readLine();
            if(!filename.endsWith(".jar")){
                System.out.println("File not in jar format.");
                System.exit(0);
            }

            File file = new File(filename);
            if (file.exists()){
                // Open the JAR file
                JarFile jarfile = new JarFile(filename);

                // Get the manifest
                Manifest manifest = jarfile.getManifest();

                // Get the main attributes in the manifest
                Attributes attrs = (Attributes)manifest.getMainAttributes();

                // Enumerate each attribute
                for (Iterator it=attrs.keySet().iterator(); it.hasNext(); ) {
                    // Get attribute name
                    Attributes.Name attrName = (Attributes.Name)it.next();
                    System.out.print(attrName + ": ");

                    // Get attribute value
                    String attrValue = attrs.getValue(attrName);
                    System.out.print(attrValue);
                    System.out.println();
                }
            }
            else{
                System.out.print("File not found.");
                System.exit(0);
            }
        }
        catch (IOException e) {}
    }
}

5
2017-12-16 12:09



运用 (-> (java.util.jar.JarFile. "myjarfile.jar") (.getManifest) (.getMainAttributes) (.getValue "Main-Class") ) - Vi.


我知道这是一个老问题,但至少在JDK 1.7中,之前提出的解决方案似乎不起作用。 出于这个原因,我发帖是我的:

JarFile j = new JarFile(new File("jarfile.jar"));
String mainClassName = j.getManifest().getMainAttributes().getValue("Main-Class");

其他解决方案对我不起作用的原因是因为 j.getManifest().getEntries() 结果是不包含Main-Class属性,而是包含在getMainAttributes()方法返回的列表中。


6
2018-01-22 15:05





这只有在罐子自动执行时才有可能;在这种情况下,将使用密钥在清单文件中指定主类 Main-Class:

这里提供了一些参考信息: http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

您需要下载jarfile然后使用 java.util.JarFile 访问它;一些Java代码可能是:

JarFile jf = new JarFile(new File("downloaded-file.jar"));
if(jf.getManifest().getEntries().containsKey("Main-Class")) {
    String mainClassName = jf.getManifest().getEntries().get("Main-Class");
}

5
2017-12-16 12:08



是的,它是自动执行的。我想获得该名称而无需手动解析思想清单文件。 - Vi.