简体   繁体   中英

After creating JAR file, command line returns 'Error: Could not find or load main class ExampleProgram`?

JAR file will not run, instead returns

Error: Could not find or load main class ExampleProgram
Caused by: java.lang.NoClassDefFoundError: ExampleProject/ExampleProgram (wrong name: ExampleProgram)

I've tried deleting the class file, then re-creating the JAR file. I've tried deleting and re-creating the program from scratch. I've tried creating the JAR file without a manifest.

package ExampleProject;

public class ExampleProgram {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

This is the exact process in how I tried to create the JAR file on the command-line.

Josephs-MBP:program jepappano4$ ls
ExampleProgram.class    ExampleProgram.java
Josephs-MBP:program jepappano4$ java ExampleProgram
Error: Could not find or load main class ExampleProgram
Caused by: java.lang.NoClassDefFoundError: ExampleProject/ExampleProgram (wrong name: ExampleProgram)
Josephs-MBP:program jepappano4$ ls
ExampleProgram.class    ExampleProgram.java
Josephs-MBP:program jepappano4$ ls
ExampleProgram.class    ExampleProgram.java manifest.mf
Josephs-MBP:program jepappano4$ jar -cvfm myprogram.jar manifest.mf *.class
added manifest
adding: ExampleProgram.class(in = 450) (out= 301)(deflated 33%)
Josephs-MBP:program jepappano4$ java -jar myprogram.jar
Error: Could not find or load main class ExampleProgram
Caused by: java.lang.NoClassDefFoundError: ExampleProject/ExampleProgram (wrong name: ExampleProgram)

I am following a tutorial on creating JAR files and I expected this process to work, but it doesn't. What am I doing incorrect here?

Not sure if this is important or not, however, I am using Java 11.

The 'wrong name' error is the key error here. This is what it means:

In java, the full name of a class is its package, followed by a dot, followed by the classname. So, your full name for this class is ExampleProject.ExampleProgram .

To start them, you must put this full name in yor manifest: It needs to have an entry that looks like:

Main-Class: ExampleProject.ExampleProgram

In addition, folder structure must match the dots. So, the jar file (which is really just a zip file) must contain inside it at the root level a directory named ExampleProject and this dir needs a file named ExampleProgram.class .

You've gotten one or both of those wrong, causing this error. You can check the structure of your jar file as follows:

jar tvf myjar.jar

you should see a listing for:

ExampleProject/ExampleProgram.class

in that precise location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM