jvm查找和加载classes
通常情况下我们只需要指定User classes即可,Bootstrap classes 和 Extension classes由jvm自动寻找,当然我们也可以改变jvm的默认行为。
User classes加载规则
1. The default value, ".", meaning that user class files are all the class files in the current directory (or under it, if in a package).
2. The value of the CLASSPATH environment variable, which overrides the default value.
3. The value of the -cp or -classpath command line option, which overrides both the default value and the CLASSPATH value.
4. The JAR archive specified by the -jar option, which overrides all other values. If this option is used, all user classes must come from the specified archive.
2. The value of the CLASSPATH environment variable, which overrides the default value.
3. The value of the -cp or -classpath command line option, which overrides both the default value and the CLASSPATH value.
4. The JAR archive specified by the -jar option, which overrides all other values. If this option is used, all user classes must come from the specified archive.
搜索顺序为:当前目录(.),${CLASSPATH}变量,-classpath(缩写-cp)
注意:当时用了java -jar xxx.jar则所有的用户classes只能在xxx.jar中查找,即使指定或者配置CLASSPATH也无用。
注意:如果使用了-classpath,JVM就不会再搜索环境变量中定义的CLASSPATH路径。
执行加载示例
应用jar包:weixin-api-0.0.1-SNAPSHOT.jar
应用相关依赖包:./lib下
指定user classes
应用jar包:weixin-api-0.0.1-SNAPSHOT.jar 相关依赖:./lib下 java -cp .;E: mplib*;weixin-api-0.0.1-SNAPSHOT.jar cn.xk.dp.weixin.Test java -classpath .;.lib*;weixin-api-0.0.1-SNAPSHOT.jar cn.xk.dp.weixin.Test 注意:-classpath通配符正确使用方式,不能是*.jar 注意:linux下用":"冒号分隔,windows下用";"分号分隔 还可以通过设置CLASSPATH变量,不用手动指定-cp E: mp>SET CLASSPATH=.;E: mplib*;E: mpweixin-api-0.0.1-SNAPSHOT.jar E: mp>java cn.xk.dp.weixin.Test 2020-03-04 16:01:38.713 main [INFO ] cn.xk.dp.weixin.Test (Test.java:33) Hello World
指定Bootstrap classes(不推荐)
-Xbootclasspath:完全取代系统Java classpath.最好不用。 -Xbootclasspath/a: 在系统class加载后加载。一般用这个。 -Xbootclasspath/p: 在系统class加载前加载,注意使用,和系统类冲突就不好了. java -Xbootclasspath/a:.;.liblog4j-api-2.13.0.jar;weixin-api-0.0.1-SNAPSHOT.jar cn.xk.dp.weixin.Test
指定Extension classes(不推荐)
java -Djava.ext.dirs="%JAVA_HOME%jrelibext";E: mplib -cp weixin-api-0.0.1-SNAPSHOT.jar cn.xk.dp.weixin.Test