import java.io.File; public class Test { public static void main(String[] args) { printPath("java.class.path"); } public static void printPath(String name) { System.out.println(name + ":"); String[] paths = System.getProperty(name).split(File.pathSeparator); for(String path : paths) { System.out.println("- " + path); } } }
执行结果:
java.class.path: - D:\sde\git-workspace\JavaSamples\java-samples-ClassPath\ClassPath\target\classes
D:\sde\git-workspace\JavaSamples\java-samples-ClassPath\ClassPath
是项目目录java -classpath ...
java -cp ...
是 java -classpath ...
的简写.class
文件目录cmd> java -cp target\classes test.Test java.class.path: - target\classes
D:\sde\git-workspace\JavaSamples\java-samples-ClassPath\ClassPath
目录执行的命令.jar
文件cmd> java -cp target\ClassPath.jar test.Test java.class.path: - target\ClassPath.jar
D:\sde\git-workspace\JavaSamples\java-samples-ClassPath\ClassPath
目录执行的命令.jar
文件目录cmd> java -cp target test.Test 错误: 找不到或无法加载主类 test.Test cmd> java -cp target\ test.Test 错误: 找不到或无法加载主类 test.Test cmd> java -cp target\*.jar test.Test 错误: 找不到或无法加载主类 test.Test cmd> java -cp target\* test.Test java.class.path: - target\ClassPath.jar
D:\sde\git-workspace\JavaSamples\java-samples-ClassPath\ClassPath
目录执行的命令java -cp
无法自动查找target
目录下的.jar
文件,并加载。target\*
可以让java自动搜索其下的.jar
文件,并加载。自JDK 1.2以后,JVM采用了委托(delegate)模式来载入class.
采用这种设计的原因可以参考: http://java.sun.com/docs/books/tutorial/ext/basics/load.html