开发者

Java will -classpath option add or replace CLASSPATH environment variable

Will the use of -classpath option with java add to or replace the contents of the CLASSPATH environment var开发者_StackOverflow中文版iable?


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.


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 (.).


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜