java -jar 和 java -cp 区别
原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12022527.html
Project Directory
SRC
MainTest.java
1 package org.fool.test; 2 3 public class MainTest { 4 public static void main(String[] args) { 5 System.out.println("Hello Jar"); 6 } 7 }
Maven Dependency
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>org.fool.test</groupId> 8 <artifactId>hello-jar</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <build> 12 <plugins> 13 <plugin> 14 <groupId>org.apache.maven.plugins</groupId> 15 <artifactId>maven-compiler-plugin</artifactId> 16 <version>3.8.1</version> 17 <configuration> 18 <source>1.8</source> 19 <target>1.8</target> 20 </configuration> 21 </plugin> 22 23 <plugin> 24 <groupId>org.apache.maven.plugins</groupId> 25 <artifactId>maven-assembly-plugin</artifactId> 26 <version>3.2.0</version> 27 <configuration> 28 <appendAssemblyId>false</appendAssemblyId> 29 <descriptorRefs> 30 <descriptorRef>jar-with-dependencies</descriptorRef> 31 </descriptorRefs> 32 <archive> 33 <manifest> 34 <mainClass>org.fool.test.MainTest</mainClass> 35 </manifest> 36 </archive> 37 </configuration> 38 <executions> 39 <execution> 40 <id>make-assembly</id> 41 <phase>package</phase> 42 <goals> 43 <goal>single</goal> 44 </goals> 45 </execution> 46 </executions> 47 </plugin> 48 </plugins> 49 </build> 50 51 </project>
Note:
maven-assembly-plugin 中指定了 mainClass
clean package 后分别执行
java -jar
1 $ java -jar hello-jar-1.0-SNAPSHOT.jar 2 Hello Jar
java -cp
1 $ java -cp hello-jar-1.0-SNAPSHOT.jar org.fool.test.MainTest 2 Hello Jar
maven-assembly-plugin 中不指定 mainClass
clean package 后再次分别执行
java -jar
1 $ java -jar hello-jar-1.0-SNAPSHOT.jar 2 no main manifest attribute, in hello-jar-1.0-SNAPSHOT.jar
java -cp
1 $ java -cp hello-jar-1.0-SNAPSHOT.jar org.fool.test.MainTest 2 Hello Jar
Reference
强者自救 圣者渡人