Why do I have to use java -cp . (class name) and not java (class name)?

冷暖自知 提交于 2019-12-11 12:07:41

问题


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 ?


回答1:


When you are launching a JVM using the java command, the JVM's classpath is determined as follows:

  • 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.

  • Otherwise, if you use the "-cp" option, the option's value gives the 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. ".".


Now you say that you have to explicitly give "-cp ." in order for the java command to execute your commands correctly.

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".




回答2:


The option -cp is used to add a path to a directory or files that the Java Environment will load for only that execution. Those files "will contains the references to the libraries" you use in your program. Alternatively to use the -cp you can set the classpath permanently. The way of setting it depends on the operating system you use. More information here: http://docs.oracle.com/javase/tutorial/essential/environment/paths.html



来源:https://stackoverflow.com/questions/18385353/why-do-i-have-to-use-java-cp-class-name-and-not-java-class-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!