Files
Knowledge/0 编程/java/java -cp 参数.md
T

39 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
cp参数就是classpath
```shell
java -cp ".;dir/;dir/a.jar;dir/b.jar" Main
```
从java1.6开始,cp参数支持通配符匹配jar文件。需要注意两点:
1. 用引号`"`
2. 用`*`,而不是`*.jar`
##### Windows:
```shell
java -cp "Test.jar;lib/*" my.package.MainClass
```
##### Linux:
```shell
java -cp "Test.jar:lib/*" my.package.MainClass
```
若不支持通配符,bash shell支持用以下方式:
```shell
java -cp $(echo lib/*.jar | tr ' ' ':')
```
其中先执行`$()`括号中的命令`echo lib/*.jar | tr ' ' ':'`,然后把`$(echo lib/*.jar | tr ' ' ':')`部分替换为命令返回的字符串,再执行替换后的`java`命令。
`tr ' ' ':'`会把`空格`替换为`:`
##### 注意:
- `-cp "foo/*"`只表示foo目录下的jar,不包括foo下的class,若要包括则用`-cp "foo;foo/*"`或`-cp "foo/*;foo"`,这里的顺序会决定是先加载jar还是class。
- `foo/*`不会递归加载foo下子目录的jar。
- `foo/*`加载foo目录下的jar顺序不是固定的,所以程序不应该依赖固定的顺序。若需要依赖则用枚举方式而不是通配符方式添加。
- manifest.mf中的Class-Path不支持通配符。