Java -classpath option

ⅰ亾dé卋堺 提交于 2019-11-29 06:06:41

问题


Will the use of -classpath option with java, add to or replace the contents of the CLASSPATH env variable?


回答1:


Using the classpath variable it overrides the CLASSPATH of Environment variable but only for that session. If you restart the application you need to again set the classpath variable.




回答2:


Yes. Quoted from the java(1) man page:

   -classpath classpath
   -cp classpath
          Specifies a list of directories, JAR archives, and ZIP archives to search  for  class  files.   Class
          path  entries  are separated by colons (:). Specifying -classpath or -cp overrides any setting of the
          CLASSPATH environment variable.

          If -classpath and -cp are not used and CLASSPATH is not set, the user class path consists of the cur-
          rent directory (.).



回答3:


Either one of the options is used, not both.

Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.

...

The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

...

Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.




回答4:


The usage of -cp option will not affect the CLASSPATH environment variable.

You can try this small code snippet to check this:

public class CPTest {
    public static void main (final String[] args) {
        String cp = System.getenv("CLASSPATH");
        System.out.println(cp);
    }
}
%echo $CLASSPATH  
/home/test/:.

The output without -cp option:

%java CPTest  
/home/test/:.

The output with -cp option:

%java -cp /home/xanadu:. CPTest  
/home/test/:.

The output is same for both invocations (one with -cp and one without).

Also either the path specified in the CLASSPATH environment variable is
used or the path specified with -cp option is used. It is not a mix of both it is one of them.

This is evident from the below invocation. If the CWD (current working directory ".")
is excluded from -cp option, the JVM launcher (i.e. java) cannot find the
class file despite the CLASSPATH environment variable containing CWD (".") in it.

%java -cp /home/test CPTest
Exception in thread "main" java.lang.NoClassDefFoundError: CPTest


来源:https://stackoverflow.com/questions/2161468/java-classpath-option

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