NullPointerException when trying to run .jar file

夙愿已清 提交于 2019-11-28 01:52:38

From the JDK doc:

In order for this option to work, the manifest of the JAR file must contain a line of the form

Main-Class: classname

Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You have to set the entry point

 $> echo "Main-Class: randommouse" > Manifest
 $> jar cfm randommouse.jar Manifest randommouse.class 

Did you specify the entry point in the manifest?

http://download.oracle.com/javase/tutorial/deployment/jar/appman.html

A couple of issues with your code that are not related to your actual problem, but are important nevertheless.

1) This statement is unnecessary:

 import java.lang.*;

By default, every class in java.lang is implicitly imported. You don't need to do it explicitly.

2) This is dangerously bad code:

    try {  
            // ...
    } catch (AWTException e) {
    } catch (InterruptedException e) {
    } catch (NullPointerException e) {  
    }

You are catching exceptions that are most likely due to programming errors, and throwing away all evidence that they ever happened. At the very least, you should print out some kind of error message ... and the exception stacktrace to that you can diagnose it.

In this particular context (in a main method), the following is a better approach:

    try {  
            // ...
    } catch (Throwable e) {
        System.err.println("An unexpected error has occurred:");
        e.printStacktrace(System.err);
        System.exit(1); 
    }

I took a look at the source code of the class and it seems to try to get the main class attribute from a list of attributes, which are Strings, and is then invoking the trim() method on the found main class attribute. When the main class is not being specified, there is no main class attribute, which causes the searching method to return null to indicate so, and when trim() is being invoked on it, it is causing the NullPointerException since the searching method has returned null. To avoid this, be sure that the main class is specified in the jar manifest:

[directory of class files]>jar -cvmf [name of manifest] MyApp.jar

And be sure that you have written the manifest right (with the line break at the end):

Main-Class: [name of main class]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!