为什么我必须使用 java -cp .(类名)而不是java(类名)? [英] Why do I have to use java -cp . (class name) and not java (class name)?
问题描述
我只是好奇为什么在像我这样的系统上,我必须使用 java -cp .只是在终端窗口中使用 java 命令不起作用?
I was just curious why on some systems like mine, I have to utilize java -cp . and simply using the java command in the terminal window doesn't work ?
推荐答案
当您使用 java
命令启动 JVM 时,JVM 的类路径确定如下:
When you are launching a JVM using the java
command, the JVM's classpath is determined as follows:
如果您使用-jar"选项,则类路径由 JAR 文件本身以及 JAR 文件中的可选类路径"属性组成.
If you use the "-jar" option, then the classpath consists of the JAR file itself, and together with the optional "Classpath" attribute in the JAR file.
否则,如果您使用-cp"选项,则该选项的值会提供类路径
Otherwise, if you use the "-cp" option, the option's value gives the classpath
否则,如果设置了 CLASSPATH 环境变量,则会给出类路径
Otherwise, if the CLASSPATH environment variable is set, then that gives the classpath
否则,类路径只包含当前目录;即.".
Otherwise, the classpath consists of just the current directory; i.e. ".".
现在你说你必须明确给出-cp".以便 java
命令正确执行您的命令.
Now you say that you have to explicitly give "-cp ." in order for the java
command to execute your commands correctly.
最可能的解释是您将 CLASSPATH 环境变量设置为不适当的值.当您运行 java MyClass
时,它会在 CLASSPATH 指定的类路径上查找……并失败.但是,当您添加-cp ."时,您是在说忽略 CLASSPATH 并只查看当前目录".
The most likely explanation is that you have the CLASSPATH environment variable set to something inappropriate. When you run a java MyClass
, it will be looking on the classpath specified by CLASSPATH ... and failing. But when you add "-cp .", you are saying "ignore CLASSPATH and just look in the current directory".
这篇关于为什么我必须使用 java -cp .(类名)而不是java(类名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!