簡體   English   中英

如何僅使用 javac 和 jar 編譯和運行可運行的 JAR

[英]How to compile and run a runnable JAR using only javac and jar

如何僅使用javacjar編譯和運行可運行的 JAR 文件? I don't want to build the JAR file with an IDE or with tools like Gradle, Maven, or Ant, because I want to understand, for my own edification, how I can compile a runnable JAR using only javac and jar , and then如何正確運行此 JAR 和java

我試過像這樣構建 JAR:

$ javac Example.java
$ file Example.class
Example.class: compiled Java class data, version 55.0
$ jar cvf Example.jar Example.class
added manifest
adding: Example.class(in = 682) (out= 456)(deflated 33%)
$ file Example.jar
Example.jar: Java archive data (JAR)

然后我嘗試了各種方法來執行 JAR,但都沒有奏效:

$ java -jar Example.jar main
no main manifest attribute, in Example.jar
$ java -cp '.;Example.jar' main
Error: Could not find or load main class main
Caused by: java.lang.ClassNotFoundException: main
$ java -cp '.;Example.jar' Example
Error: Could not find or load main class Example
Caused by: java.lang.ClassNotFoundException: Example
$ java -cp '.;Example.jar' -jar Example.jar Example
no main manifest attribute, in Example.jar
$ java -cp '.;Example.jar' -jar Example.jar main
no main manifest attribute, in Example.jar

我的代碼,只是為了顯示我有一個Example class 和一個main() function:

import java.util.ArrayList;
import java.util.List;

public class Example {
    private static class A {
        public int x = 7;
    }

    public static void main(String[] args) {
        List<A> list = new ArrayList<>();
        A a = new A();
        list.add(a);
        a.x = 5;
        System.out.println(a.x);
        System.out.println(list.get(0).x);
    }
}

我的javacjarjava工具都是 11.0.15 版本。

I tried looking at the answers on Compile and run with javac and java using classpath classes in jar and javac compiles files and jars but java fails , but none of the suggestions in the answers to these two questions worked for me.

感謝@f1sh 和@pdem,我找到了答案:

$ javac Example.java
$ jar cfe Example.jar Example Example.class 'Example$A.class'
$ java -jar Example.jar
5
5

Is @f1sh points out in there comment, I needed to (A) include the Example$A.class class when creating the JAR, and (B) run the java command with the correct arguments.

至於使 JAR 可執行,需要清單文件。 可以手動創建清單文件,也可以讓jar使用e選項為您創建它。 使用e選項的一般格式是

java cfe <name of jar> <name of main class> <list of .class files>

有關使用e選項或手動編寫清單文件的更多信息,請參閱設置應用程序的入口點使用清單文件:基礎知識的其他子頁面之一。

goose@t410:/tmp$ javac Example.java 
goose@t410:/tmp$ jar cvfe example.jar Example Example*.class 
added manifest
adding: Example$A.class(in = 293) (out= 233)(deflated 20%)
adding: Example.class(in = 682) (out= 457)(deflated 32%)
goose@t410:/tmp$ java -jar example.jar 
5
5

注意 jar 的倒數第二個參數是主jar的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM