java - 为什么 java.class.path 属性总是返回 jar 的位置?

标签 java executable-jar

Get location of JAR file据说“只要你的类路径只包含一个条目,这就可以[获取可运行的 jar 文件的位置]”。

这是我的代码:

   public static void main(String[] args) {
       System.out.println(System.getProperty("java.class.path"));
   }

我创建了一个可运行的 jar(使用 Eclipse Export),当我运行它时,无论我将 CLASSPATH 设置为什么,我只得到可运行的 jar 的路径。

例如:

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

我还尝试在命令行上使用 -cp。

有人能想出一个反例吗?它返回的东西比我正在运行的 jar 文件的位置更多/不是?

(了解在 Eclipse 中它返回我项目的 bin 文件夹。)

这是我唯一关心的用例:将此程序作为可运行的 jar 运行。

谢谢。

最佳答案

manual entry for java

-jar

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

当使用 -jar 选项时,.jar 本身用作整个类路径。


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?

正常情况下,不会。但是,它只是一个属性,因此您可以更改它的值。

System.setProperty("java.class.path", "garbage");

正如 nramaker 在他们的 answer 中建议的那样,您可以通过 MANIFEST 文件提供要包含在类中的其他 jar 的位置。 Java 教程解释了如何执行此操作:

但是,这不会更改 java.class.path 属性的值。如果要从 list 文件中提取 Class-Path 属性的值,可以使用以下提供的解决方案:

一个例子,

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
}

关于java - 为什么 java.class.path 属性总是返回 jar 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979136/

相关文章:

java - 我可以创建一个生成多个可执行 Jars 的 Eclipse 项目吗?

java - 从 ArrayList<MyObject> 获取 Set<String>

java - 使用 selenium 和 java 找不到类

java - 什么是原始类型,为什么我们不应该使用它呢?

java - 从 jar 创建可执行文件

java - 如何在Gradle项目中创建单个可执行jar

java - Apache Kafka 的 Spring : Unrecognized producer configuration - 'delivery.timeout.ms'

java play 框架覆盖注释失败,java.source=1.6

java - 如何使用 IntelliJ 从 Selenium/TestNG java 文件制作可执行 jar 文件?

java - 通过 "Could not find or load main class"运行可执行 JAR 时为 "java -jar"