Home >Java >javaTutorial >How to Run a JAR File with External Libraries and Avoid \'java.lang.ClassNotFoundException\'?

How to Run a JAR File with External Libraries and Avoid \'java.lang.ClassNotFoundException\'?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 20:45:03268browse

How to Run a JAR File with External Libraries and Avoid

Calling "java -jar MyFile.jar" with Extended Classpath Options

When attempting to run a compiled JAR file incorporating external libraries and facing a "java.lang.ClassNotFoundException", it's crucial to understand the fundamentals behind the Java execution process.

Java provides two options for specifying classpaths:

  • -jar: Includes the JAR file and its manifest-defined classpath.
  • -cp: Manually specifies the complete classpath, including all dependencies.

Incorrect Usage

Attempting to combine both -jar and -cp concurrently is incorrect and will result in the aforementioned error.

Solution

There are two valid approaches to resolve this issue:

1. Manifest-Defined Classpath:

  • Create a manifest file within the JAR specifying the required classpath.
  • Use java -jar to execute the JAR, which will automatically load the specified dependencies.

2. Explicit Classpath:

  • Use java -cp to define the complete classpath, including the main JAR and all external JARs.
  • Specify the main class explicitly on the command line.

For Example:

java -cp 'MyProgram.jar:libs/*' main.Main

Note: The dir/* syntax adds all JAR files from the specified directory to the classpath.

Additional Tips:

  • For the manifest-defined approach, use Ant's task to dynamically generate the manifest file with the desired classpath before building the JAR.
  • If the -jar option is more convenient, ensure that all dependencies are included in the JAR's manifest.

The above is the detailed content of How to Run a JAR File with External Libraries and Avoid 'java.lang.ClassNotFoundException'?. 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