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."
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:
Include All Jar Files in the Manifest:
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
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!