1

The problem

I'm building a project using Gradle, but whenever I want to start the JAR manually via java -jar <the jar> it fails with the following error: Error: Could not find or load main class projectz.ProjectZ.

The description

I already figured out that I need to add the following lines to my Gradle project:

mainClassName = 'projectz.ProjectZ'

jar {
    manifest {
        attributes('Main-Class': project.mainClassName)
    }
}

However, this doesn't solve the problem. I can't execute my jar. Building the same jar with my IDE (eclipse) gives me a working jar. Copy-Pasting my META-INF folder into my JAR generated by Gradle also doesn't solve the problem.

For my setup I'm using the following plugins:

plugins {
    id 'java'
    id 'application'
    id 'eclipse'
    id 'idea'
}

My project also depends on another project (as this is a multi-project setup) imported via the Gradle dependencies: compile project (':Lib') This dependency isn't added to my jar file as well, but when I run installDist withing Gradle, it is added and I can start my JAR (thought only over some batch file Gradle puts within the folder) and java suddenly finds my main class (which is not part of the dependency, but of the main project). Trying to run my jar file over the normal java -jar <jar file> way still doesn't work.

What I tried so far

I searched for the error java gives me and added the missing lines to my build.gradle file, thought this doesn't solve the problem in my case. I also searched in the Gradle documentation to figure out if I may have missed something there, but couldn't find anything missing.

My Setup

  • fresh Java 8 installation (which my Project uses)
  • new Gradle project and setup
  • new Gradle installation using Gradle 4.10.2
Community
  • 1
  • 1
ShadowDragon
  • 2,238
  • 5
  • 20
  • 32

1 Answers1

1

The jar you are producing with your Gradle build script is a standard jar, not a fat jar (see Fat jar description), that's why you cannot execute this jar directly with java -jar <the-jar>. You have dependencies that are not included in this jar (at least code from your dependent project :Lib, and certainly other external dependencies)

So you should either change your buidld script to procude a fat jar, or use the packaged application produced by the application gradle plugin.

For building fat jar you have different solutions available, for example:

mainClassName = "org.mycompany.gradle.MainApp"
jar {
    manifest {
        attributes('Main-Class': project.mainClassName)
    }
    // HERE : include dependencies into the jar 
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

Other solutions can be found there: https://www.baeldung.com/gradle-fat-jar

M.Ricciuti
  • 11,070
  • 2
  • 34
  • 54