简体   繁体   中英

How to use java -cp and -jar in a togther

I am trying the following:

java -cp <path to the additional required jar > -jar <jarname>.jar

I am still getting a java.lang.NoClassDefFoundError when running the above command. Looks like it still cannot find the external jar mentioned after -cp. Is that the correct syntax while giving the java command?

You can't use the -jar and -classpath options together. If you want to use the -jar option you need to add the second JAR file to the Class-path attribute in the manifest of the first JAR file.

You could add the additional jar to the bootclasspath

 java -Xbootclasspath/a:additional_required.jar -jar main.jar

example

Foo.java

package foo;
public class Foo {
    public static void main(String[] args) {
        new bar.Bar();
    }
}

Bar.java

package bar;
public class Bar {
    public Bar() {
        System.out.println("foobar");
    }
}

manifest.mf

Main-Class: foo.Foo

Execute the commands

javac -d . Bar.java Foo.java
jar cf Bar.jar bar/
jar cmf manifest.mf Foo.jar foo/
java -Xbootclasspath/a:Bar.jar -jar Foo.jar

output

foobar

Given the following command you provide:

java -cp <path to the additional required jar > -jar <jarname>.jar

it will fail because the 'classpath' value must be a ' ; ' separated value. So try adding a ; after your classpath values. For example:

java -cp A.jar;Bjar; -jar <jarname>.jar

and it is mandatory even if you have only one jar file in you classpath string:

java -cp A.jar; -jar <jarname>.jar

Good Luck.

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