1. 程式人生 > 其它 >java -cp與java -jar的區別

java -cp與java -jar的區別

java -cp 和 -classpath 一樣,是指定類執行所依賴其他類的路徑,通常是類庫,jar包之類,需要全路徑到jar包,window上分號“;”
格式:
java -cp .;myClass.jar packname.mainclassname
表示式支援萬用字元,例如:
java -cp .;c:\classes01\myClass.jar;c:\classes02\*.jar packname.mainclassname


java -jar myClass.jar
執行該命令時,會用到目錄META-INF\MANIFEST.MF檔案,在該檔案中,有一個叫Main-Class的引數,它說明了java -jar命令執行的類。


用maven匯出的包中,如果沒有在pom檔案中將依賴包打進去,是沒有依賴包。
1.打包時指定了主類,可以直接用java -jar xxx.jar。
2.打包是沒有指定主類,可以用java -cp xxx.jar 主類名稱(絕對路徑)。
3.要引用其他的jar包,可以用java -classpath $CLASSPATH:xxxx.jar 主類名稱(絕對路徑)。其中 -classpath 指定需要引入的類。


下面基於pom和META-INF\MANIFEST.MF兩個檔案的配置,進行了三種情況的測試:
pom.xml的build配置:

    <build>
        <!--<finalName>test-1.0-SNAPSHOT</finalName>-->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                        <mainClass>test.core.Core</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <!--下面是為了使用 mvn package命令,如果不加則使用mvn assembly-->
                <executions>
                    <execution>
                        <id>make-assemble</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

 


META-INF\MANIFEST.MF的內容:
Manifest-Version: 1.0
Main-Class: test.core.Core


1.pom中build指定mainClass 但是 META-INF\MANIFEST.MF檔案中沒有指定Main-Class: test.core.Core
java -jar test-jar-with-dependencies.jar //執行成功
java -cp test-jar-with-dependencies.jar test.core.Core //執行失敗,提示jar中沒有主清單屬性


2.pom中build沒有指定mainClass 但是 META-INF\MANIFEST.MF檔案中指定了Main-Class: test.core.Core


java -jar test-jar-with-dependencies.jar //執行失敗,提示jar中沒有主清單屬性
java -cp test-jar-with-dependencies.jar test.core.Core //執行成功


3.pom中build指定mainClass && META-INF\MANIFEST.MF檔案中增加了Main-Class: test.core.Core
java -cp test-jar-with-dependencies.jar test.core.Core //執行成功
java -jar test-jar-with-dependencies.jar //執行成功

轉自:https://www.cnblogs.com/wqbin/p/11128596.html