0

I am trying to execute a java application, which is packaged as jar archive.

java -cp .\lib\json.jar -jar ".\myarchive.jar"

I get an error saying that the classes inside my json.jar archive cannot be found.

Exception in thread "main" java.lang.NoClassDefFoundError: json/serializers/JsonTypeResolversInstance
Caused by: java.lang.ClassNotFoundException: json.serializers.JsonTypeResolversInstance
        at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 2 more

The jar file contains the class, so i think this error should not happen. When executing the code using my IDE it runs without errors.

I have tried to fix this in many ways, without success.

1
  • 1
    The -cp option is ignored when you use -jar. See the documentation. Commented May 18, 2022 at 7:57

1 Answer 1

5

Using the -cp and -jar options at the same time does not work. When you use the -jar option, then the -cp option is ignored.

There are two ways to run code in a JAR file in Java.

First way: Use the -cp option and specify the name of the class that contains the main method on the command line. For example:

java -cp .\lib\json.jar;.\myarchive.jar com.mypackage.MyMainClass

When you do it like this, you specify the classpath on the command line (using -cp). The classpath must contain all JAR files and/or directories that contain all the classes that the application needs. You must also specify the name of the class to run on the command line.

Also, when you do it like this, the manifest file that might be present in the JAR file is ignored.

Second way: Use the -jar option. For example:

java -jar .\myarchive.jar

When you do it like this, then Java will look at the manifest file in the JAR file. The classpath and the name of the class to run will be taken from the manifest file, and the -cp option on the command line will be ignored.

For details see the documentation of the java command.

Sign up to request clarification or add additional context in comments.

1 Comment

I have previously tried the solution using the manifest file, without success. Maybe i did something wrong, so I will try it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.