In Java, there are two ways to execute a JAR file: using the -jar option or specifying the classpath with -cp. However, attempting to combine both options leads to an error.
When using -jar, the Java Virtual Machine (JVM) assumes that the JAR file contains all necessary dependencies. Therefore, specifying an additional classpath with -cp is not recommended.
Instead, there are two alternative approaches:
<code class="xml"><manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar"> <classpath> <fileset dir="libs" includes="*.jar" /> </classpath> </manifestclasspath></code>
<code class="xml"><jar destfile="MyProgram.jar" basedir="classes"> <manifest> <attribute name="Main-Class" value="main.Main" /> <attribute name="Class-Path" value="${myprogram.manifest.classpath}" /> </manifest> </jar></code>
By specifying the classpath in the manifest, java -jar MyProgram.jar will include all the dependencies.
java -cp 'MyProgram.jar:libs/*' main.Main
Using the * syntax expands to include all JAR files in the "libs" directory.
Remember, it is crucial to choose either the -jar or -cp approach. Combining both can lead to classpath conflicts and errors.
The above is the detailed content of How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?. For more information, please follow other related articles on the PHP Chinese website!