Home >Java >javaTutorial >How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?

How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 03:04:021052browse

How to Execute a JAR File with Additional Dependencies: -jar vs. -cp?

Call "java -jar MyFile.jar" with Additional Classpath Option

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:

Approach 1: Add JARs to the Main Manifest

  1. Copy the required JAR files to a subfolder, such as "libs".
  2. Use the task in Ant before building the JAR:
<code class="xml"><manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar">
  <classpath>
    <fileset dir="libs" includes="*.jar" />
  </classpath>
</manifestclasspath></code>
  1. Create the JAR with the updated manifest:
<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.

Approach 2: Specify Classpath with -cp

  1. Include all required JAR files in the classpath:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn