Home > Java > javaTutorial > How to Execute a JAR File with External Dependencies?

How to Execute a JAR File with External Dependencies?

Mary-Kate Olsen
Release: 2024-12-05 18:41:10
Original
1008 people have browsed it

How to Execute a JAR File with External Dependencies?

Executing a JAR File with an External Classpath

Problem

Compiling a JAR file with a specified Main-Class and dependent libraries (stored in the "lib" directory), attempts to execute the JAR file with the custom classpath fail. The errors encountered include "Could not find or load main class" or "NoClassDefFoundError."

Solution

The Java -jar command ignores the -cp parameter when specifying a JAR file. This means that any attempts to specify a custom classpath using -cp will be ineffective.

To execute the JAR file with the external classpath, two options are available:

  1. Include All Jar Files in the Manifest:

    • Within the MANIFEST.MF file in the JAR, specify the classpath by including the JAR files from the "lib" directory using relative paths.
  2. Specify Classpath on Command Line:

    • On the command line, specify the -cp option with a colon-separated list of all necessary JAR files, including your JAR file and the "lib" directory:

      java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
      Copy after login

Note: It's not possible to include additional JAR files within the JAR file itself, as you would need to extract and place the .class files directly into your JAR.

The above is the detailed content of How to Execute a JAR File with External Dependencies?. 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