I recently came across what seemed to be a fairly common error message while trying to run a Java jar on a newly installed Ubuntu 16.04 VM:
1 2 |
$ java -cp server.jar com.wurmonline.server.gui.WurmServerGuiMain Error: Could not find or load main class com.wurmonline.server.gui.WurmServerGuiMain |
This is a pretty common issue that usually stems from incorrect classpaths or a wrongly specified main class, which is what appears when you search for “Could not find or load main class”. I’d checked the usual suspects though, checking for:
- typos in the file name – java doesn’t tell you if any of the classpath entries don’t exist
- existence of the class – I unzipped the file to check that yes, the class exists
- typos in the package or class -copied the package and class name from the source just in case
All these checked out, so what was the issue? I noticed that there was no META-INF/Manifest.MF, which would causes java -jar to fail but doesn’t cause any issues when you’re explicitly specifying a main class – or does it? I read through the jar file specification to see if perhaps the jar wasn’t properly packaged but it indicated that META-INF and its contents were optional in this situation. Hmmm…
Double checking the WurmServerGuiMain class, I verified again that it had the correct main method signature but this time I remembered that it was a Java FX class that subclassed the javafx.application.Application class. Java FX has caused me issues in the past, partly due to the way it was introduced as an add-on ext lib, and partly due to the way it gets loaded in the case of a jnlp, but this was just a bog-standard jar file so…
Wait, do I need to explicitly include jfxrt.jar? If the parent Application class couldn’t be found, that’d be another reason for being unable to load the main class. Looking in $JAVA_HOME/jre/lib/ext, I couldn’t see the jar, so I did a little reading and found out that on Ubuntu 16.04 at least, OpenJFX is in a separate package and is not included with the OpenJDK 8 JRE. Now we’re getting somewhere! Now a quick
1 |
sudo apt-get install openjfx |
and I’m able to run the jar. Still more bugs, but at least those ones are expected.
So, two points that I’ve learnt:
- “Error: Could not find or load main class” is a more non-specific error than I thought, and can mean that your parent class cannot be found (though it won’t tell you that explicitly)
- Java FX does not always come included in the OpenJDK 8 JRE
Both seem fairly straightforward in hindsight, but at least writing it out should help in troubleshooting similar situations for myself and customers in the future.