java -jar 和 java -cp 区别

 

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

 <?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

https://www.jianshu.com/p/eabfb61e072a

https://blog.csdn.net/yulei_qq/article/details/82423683

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值