Search code examples
javaintellij-ideajarexecutable-jarintellij-14

.jar file error "could not find or load main class" with IntelliJ


This is my MainBot.java code:

public class MainBot {
    public static void main(String[] args) {
        new MainBot("my_private_token");
    }

    public MainBot(String token) {
        // do stuff
    }
}

I have the following problem: When I try to execute the .jar file generated by IntelliJ, I get the following error:

could not find or load main class: MainBot

But when I look in the .jar file using WinRAR, I see this:

jar file

The MainBot.class file is there! The manifest file in the META-INF/ folder looks like this:

Manifest-Version: 1.0
Main-Class: MainBot

And the the META-INF folder looks like this:

meta-inf

What did I do wrong? When exporting, I select the correct main file in INTELLIJ, add the META-INF directory to resources/ and then I build my artifact. How come that The MainBot file cannot be found, when it is there?! I also tried playing arond with the MAINFEST.MF file and tried changing the Main-Class to ../MainBot or something, but none of that worked.

EDIT: This is the artifact under Project Structure | Artifacts

enter image description here enter image description here


Solution

  • The META-INF folder in your generated Jar has these 2 files -

    SIGNINGGC.RSA
    SIGNINGGC.SF
    

    I assume that you are not signing the Jar. Then, these files must be coming from one of your dependancies when you are creating a Fat Jar. If any of your dependancies has a Signed Jar, then it could result into that could not find or load main class: exception.

    You can quickly find if this is the issue by removing those files with this command (referenced from here) and try and run the code -

    zip -d yourjar.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*.DSA'
    

    IntelliJ shows 2 Options while generating Jar. The first one will generate a Fat Jar. The other option will keep the other library jars intact and link with them using Manifest file.

    Assuming all you need is to run your code, use the second option in the Create Jar from Modules Dialog box.

    enter image description here