Java "-cp" 选项,编译时还是运行时?

Java "-cp" option, compile time or runtime?

我看到有人说有不同类型的类路径。例如编译时类路径和运行时类路径。

我猜 "-cp""-classpath" 选项与 javac 一起使用时是编译时类路径。

并且当与 java 命令一起使用时,它应该是运行时类路径。我说得对吗?

这两个类路径可以完全不同吗?

I guess the "-cp" or "-classpath" option when used with javac is compile time classpath.

没错。

来自java Docs

The JDK tools java, jdb, javac, and javah have a -classpath option which replaces the path or paths specified by the CLASSPATH environment variable while the tool runs. This is the recommended option for changing class path settings, because each application can have the class path it needs without interfering with any other application.

The runtime tool java has a -cp option, as well. This option is an abbreviation for -classpath.

For very special cases, both java and javac have options that let you change the path they use to find their own class libraries. The vast majority of users will never to need to use those options, however.

javajavac 命令接受 -cp-classpath ... 含义相同。

曾几何时,javac只接受-classpath


Can these two classpaths [used by java and javac] be completely different?

他们可以。但是,如果您使用一个版本的 API 和 运行 编译另一个版本,您可能 运行 进入 "binary compatibility" 导致 运行 时间的问题错误。

因此,建议在编译时和运行时使用相同(或等效)的类路径。


Why the same content two times?

因为内容(类路径)没有被编译到代码中。

更深入的答案是,Java 程序通常由独立编译的组件(例如库)组成,然后在您 运行 应用程序时组合在一起。每个组件构建都需要不同的类路径……根据其依赖项。当您将所有部分放在一起时,可能需要再次使用不同的类路径。因此需要能够在编译和 运行 时间指定不同的类路径。

I guess the "-cp" or "-classpath" option when used with javac is compile time classpath.

完全正确!

Can these two classpaths be completely different?

最好这两个相同。

否则,如果某些 class 在编译时存在(并且实际在您的代码中使用),但在运行时丢失,则可能会出现 NoClassDefFoundError 错误。

class路径可以只有在编译时将classes添加到class路径时才会不同,它们是未在您的来源中使用。在这种情况下,您可以跳过将这些添加到运行时 class 路径。

但是,我建议您保持 class路径中不需要的 classes/libraries。

我猜与 javac 一起使用时的“-cp”或“-classpath”选项是编译时类路径。

yes

这两个类路径可以完全不同吗?

they should be same

for any given class, the java virtual machine will need to find exactly the same supporting classes that the javac compiler needed to find at compilation time.In other words, if javac needed access to java.util.HashMap then the java command will need to find java.util.HashMap as well.