Home > Java > javaTutorial > How to Run a JAR File with External Dependencies from the Command Line?

How to Run a JAR File with External Dependencies from the Command Line?

Linda Hamilton
Release: 2024-12-16 13:18:15
Original
467 people have browsed it

How to Run a JAR File with External Dependencies from the Command Line?

Executing JAR Files with a Custom Classpath from the Command Line

When running a JAR file that relies on external dependencies, specifying the appropriate classpath is crucial. This issue arises when attempts to execute a JAR file with a specified classpath directory (lib/*) fail to load the main class or find required libraries.

The solution lies in understanding the behavior of the -jar option. When used, it supersedes other classpath settings specified with -cp. This is stated in the documentation:

"When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored."

Therefore, including dependencies as part of the JAR file or altering the classpath using -jar is not feasible.

To successfully execute the JAR file with the desired classpath, consider these options:

Option 1: Include Dependencies in JAR Manifest

  • Add all necessary JAR files from the lib directory to the JAR's manifest using relative paths.
  • For example, if the target JAR file is named MyJar.jar and the dependencies are in lib/dependency1.jar, lib/dependency2.jar, and so on, the manifest entry would be as follows:
Class-Path: lib/dependency1.jar lib/dependency2.jar
Copy after login

Option 2: Specify Classpath on Command Line

  • Use the -cp option to specify both the JAR file and the classpath directory:
java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
Copy after login

This approach must account for all necessary JAR files, including the main JAR itself.

The above is the detailed content of How to Run a JAR File with External Dependencies from the Command Line?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template