In Get location of JAR file it was said that "This works [to get the location of a runnable jar file] only so long as you classpath contains just one entry".
This is my code:
public static void main(String[] args) {
System.out.println(System.getProperty("java.class.path"));
}
I create a runnable jar (using Eclipse Export), and when I run it, regardless of what I set CLASSPATH to, I only get the path of the runnable jar.
For example:
C:\TEMP>set CLASSPATH=C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>echo %CLASSPATH%
C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>set CLASSPATH
CLASSPATH=C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>java -jar C:\Programs\bin\Test_one_prop.jar
C:\Programs\bin\Test_one_prop.jar
I also tried using -cp on the command line.
Can some one come up with a counter-example where this returns something more/other than the location of the jar file I'm running?
(Understood that in Eclipse it returns my project's bin folder.)
This is the only use case I'm concerned with: running this program as a runnable jar.
Thanks.
The manual entry for java
states
-jar
[...]
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
When using the -jar
option, the .jar
itself is used as the entire classpath.
Can some one come up with a counter-example where this returns something more/other than the location of the jar file I'm running?
Under normal circumstances, no. However, it's just a property, so you can change its value.
System.setProperty("java.class.path", "garbage");
As nramaker suggests in their answer, you can provide the location of other jars to include in the class through the MANIFEST file. The Java tutorials explain how to do this:
However, this won't change the value of the java.class.path
property. If you want to extract the value of the Class-Path
attribute from a manifest file, you can use the solutions provided in:
One example,
URLClassLoader cl = (URLClassLoader) Example.class.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
System.out.println(manifest.getMainAttributes().getValue(new Attributes.Name("Class-Path")));
} catch (IOException e) {
// handle
}
When you run an executable jar file the classpath is defined by what's in the manifest file inside the jar file. This overrides whatever is passed on the command line or set in the environment.
http://anshuiitk.blogspot.com/2010/10/class-path-settings-in-excecutable-jar.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With