Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Classpath and relative paths

Tags:

java

classpath

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
like image 617
rubixibuc Avatar asked May 11 '13 23:05

rubixibuc


People also ask

What are relative paths in Java?

A relative path is a path which doesn't start with the root element of the file system. It is simply the path needed in order to locate the file from within the current directory of your program. It is not complete and needs to be combined with the current directory path in order to reach the requested file.

What is the concept of CLASSPATH in Java?

Classpath is a parameter in the Java Virtual Machine or the Java compiler that specifies the location of user-defined classes and packages. The parameter may be set either on the command-line, or through an environment variable.

What is Build path and CLASSPATH in Java?

Build path is used by the compiler to resolve dependencies and build a project. Classpath is used during runtime when running a project in order to find necessary dependencies. Build path is configured on the Java Build Path property page of a project.


1 Answers

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
like image 90
Stephen C Avatar answered Oct 14 '22 00:10

Stephen C