I can make a executable jar file with Eclipse. Let's say it is called ast.jar
, and the Main class is ASTExplorer. I can verify that this works with java -jar ast.jar
.
Then, I unzip the jar file in a separate directory and verify that the ASTExplorer is in astexplorer directory. But when I executed this command java -cp . astexplorer.ASTExplorer
I get this error.
java -cp . astexplorer/ASTExplorer
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/swt/widgets/Composite
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
The thing is that there is no org/eclipse/swt directory in the jar file.
What's the magic behind the executable jar file? Why doesn't it run when unzipped?
A Java Archive, or JAR file, contains all of the various components that make up a self-contained, executable Java application, deployable Java applet or, most commonly, a Java library to which any Java Runtime Environment can link.
The Jar File wizard can be used to export the content of a project into a jar file. To bring up the Jar File wizard − In the Package Explorer select the items that you want to export. If you want to export all the classes and resources in the project just select the project. Click on the File menu and select Export.
Right click on your Java Project and select Export. Select Java -> Runnable JAR file -> Next. Select the Destination folder where you would like to save it and click Finish.
When Eclipse packages a runnable jar, it includes the dependencies as nested jar files, and also includes a special classloader that understands how to find classes in nested jars. It works only with nested jars and when you extract everything you prevent it from working.
I've looked in an Eclipse-produced runnable jar, and here's what I think you'd need to do:
Run your main class from the top level directory with
java -cp .;dep-jar;dep-jar;... your.main.class
I tried this with a runnable jar I happen to have lying around and it works. Step 2 isn't strictly necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With