Java Classpath and relative paths

2020-07-10 05:41发布

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

2条回答
【Aperson】
2楼-- · 2020-07-10 05:56

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

查看更多
在下西门庆
3楼-- · 2020-07-10 06:05

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:

查看更多
登录 后发表回答