简体   繁体   中英

Does java -jar option alter classpath options

I have a jar file which mentions the main class in the manifest. When I try to execute the jar using the following command

java -cp .;./* com.foo.MainClass

The code executes and works.

When I try to execute the jar using the following command

java -cp .;./* -jar myjar.jar

I get class not found execptions for some jars which are in the same folder as myjar.jar. I hoping that the -cp option will include those jars in class path. I modified my code to print java.class.path property. In the first case it listed all jars in the current directory, in second case it just listed myjar.jar

I also modified the manifest to add Class-Path element to it with all jars. Then the second command works. But in my code I am trying to load a aribtrary class whose name is provided at command prompt, so I want the class path to contain all jars in a folder. How do I make the second command work in this scenario?

From this ,

An executable JAR must reference all the other dependent JARs it requires through the Class-Path header of the manifest file. The environment variable CLASSPATH and any class path specified on the command line is ignored by the JVM if the -jar option is used.

是对这个问题的一个很好的讨论。

You will need your own classloader to deal with this. -jar only respects the information in the Manifest and wildcards are not allowed there.

You might find the example of a reloadable class useful: http://www.exampledepot.com/egs/java.lang/ReloadClass.html

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