Java Classpath and relative paths

倖福魔咒の 提交于 2019-12-09 16:43:30

问题


If you have a relative path in the java class path, does this just search the current working directory. Does the same hold for class paths declared in a manifest file. In a manifest file is it relative to the dir the jar is in?

Ex. Cmdline

java -cp somejar.jar

Or

Manifest

Class-Path: somejar.jar

回答1:


If you say -cp somejar.jar you are adding somejar.jar to the classpath. It will only try to find the somejar.jar from the directory you are currently in when you typed the command.

If you say in the Manifest

Class-Path: somejar.jar

you are saying add the jar, somejar.jar into the classpath from the directory where the manifest is located(aka inside the jar).

As a side note, when you specify the classpath by using -jar, -cp, or -classpath, you override the system variable CLASSPATH.

More details can be found here, http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html




回答2:


You've actually mentioned two different cases:

Case #1

java -cp foo/bar/somejar.jar ...

In this case the relative path to the JAR (or whatever) is resolved relative to the current directory.

Case #2

java -jar foo/bar/somejar.jar ...

where somejar.jar contains

Class-Path: anotherjar.jar

In this case "foo/bar/somejar.jar" is resolved relative to the current directory (as above), but "anotherjar.jar" is resolved relative to the directory containing "somejar.jar".

(Aside: my understanding is that a Manifest Class-Path: attribute is respected when a JAR file is included via -cp or $CLASSPATH, but it only affects the dependencies of classes loaded from that JAR ... see the "findingclasses" link below.)

References:

  • http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
  • http://docs.oracle.com/javase/7/docs/technotes/tools/findingclasses.html
  • http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html
  • http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html


来源:https://stackoverflow.com/questions/16502663/java-classpath-and-relative-paths

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!