简体   繁体   中英

Why Java needs classpath at runtime

In Java we set the classpath at compile time to compile Java files, but why do we need to set the classpath at runtime? Any specific reason why the JVM needs the classpath to run .class files?

类路径上的文件提供了JVM需要运行的实际可执行代码(在Java .class文件中)。

In Java we set the classpath at compile time to compile Java files

Do we? I don't.

but why do we need to set the classpath at runtime?

So the JVM knows where it can find the classes.

One of the reasons that I see, is that if I need for some reasons to have the libraries required by my app scattered across multiple mountpoints/drives/partitions or even folders, I would not be able to specify to the JVM where my code is. As a workaround, the JVM could look throughout the whole file-system and index stuff, but how efficient/fast would that be?

Cheers

Often people think compiling makes for a stand-alone application without the need to point at dependencies. But it does not.

If your code has no dependencies, then you do not need to set a classpath.

You may need/want to include -cp at runtime:

  1. To specify where to look for third-party and user-defined files your class requires at runtime (*.jar, *.class, *.properties, etc).

  2. To override what the CLASSPATH environment variable is set to.

CLASSPATH is an environmental variable used by Java Virtual Machine to locate the class files(including main class).

Alternatively you can pass -cp or -class-path as a argument to JVM to specify the class paths where your main class depends on.

For example,

export CLASSPATH=/opt/javatv:/opt/mhp:/opt/main-class;
java MainClass

(or)

java -cp /opt/javatv;/opt/mhp;/opt/main-class MainClass;

(or)

java -class-path /opt/javatv;/opt/mhp;/opt/main-class MainClass;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM