[java] Gradle - Could not find or load main class

I'm trying to run a very simple project using Gradle and running into the following error when using the gradlew run command:

could not find or load main class 'hello.HelloWorld'

Here is my file structure:

SpringTest
    -src
        -hello
            -HelloWorld.java
            -Greeter.java
    -build
         -libs
         -tmp
    -gradle
         -wrapper
    -build.gradle
    -gradlew
    -gradlew.bat

I excluded the contents of the libs and tmp folders because I didn't think that would be relevant information for this issue, but I can add it in if need be.

Here is my build.gradle file:

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'

mainClassName = 'hello/HelloWorld'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    compile "joda-time:joda-time:2.2"
}

jar {
    baseName = "gs-gradle"
    version = "0.1.0"
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

Any idea on how to fix this issue? I've tried all sorts of things for the mainClassName attribute but nothing seems to work.

This question is related to java spring gradle build.gradle

The answer is


Just to make it clear for newbies trying to run a gradle project from Netbeans:
To understand this, you need to see what the main class name looks like and what the gradle build looks like:

Main class:

package com.stormtrident;

public class StormTrident {
    public static void main(String[] cmdArgs) {
    }
}

Notice that it is part of the package "com.stormtrident".

Gradle build:

apply plugin: 'java'

defaultTasks 'jar'

jar {
 from {
        (configurations.runtime).collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }    
    manifest {
        attributes 'Main-Class': 'com.stormtrident.StormTrident'
    }
}


sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

if (!hasProperty('mainClass')) {
    ext.mainClass = 'com.stormtrident.StormTrident'
}

repositories {
    mavenCentral()
}

dependencies {
    //---apache storm
    compile 'org.apache.storm:storm-core:1.0.0'  //compile 
    testCompile group: 'junit', name: 'junit', version: '4.10'
}

For Netbeans 11 users, this works for me:

apply plugin: 'java'
apply plugin: 'application'

// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'

Here generally is my tree:

C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦   build.gradle
+---src
¦   +---main
¦   ¦   +---java
¦   ¦       +---com
¦   ¦           +---hello
¦   ¦                   JavaApplication1.java
¦   ¦
¦   +---test
¦       +---java
+---test

I just ran into this problem and decided to debug it myself since i couldn't find a solution on the internet. All i did is change the mainClassName to it's whole path(with the correct subdirectories in the project ofc)

    mainClassName = 'main.java.hello.HelloWorld'

I know it's been almost one year since the post has been made, but i think someone will find this information useful.

Happy coding.


  1. verify if gradle.properties define right one JAVA_HOVE

    org.gradle.java.home=C:\Program Files (x86)\Java\jdk1.8.0_181

or

  1. if it's not defined be sure if Eclipse know JDK and not JRE

enter image description here


If you decided to write your hello.World class in Kotlin, another issue might be that you have to reference it as mainClassName = "hello.WorldKt".

src/main/java/hello/World.kt:

package hello
fun main(args: Array<String>) {
    ...
}
// class World {} // this line is not necessary

When I had this error, it was because I didn't have my class in a package. Put your HelloWorld.java file in a "package" folder. You may have to create a new package folder:

Right click on the hello folder and select "New" > "Package". Then give it a name (e.g: com.example) and move your HelloWorld.java class into the package.


For a project structure like

project_name/src/main/java/Main_File.class

in the file build.gradle, add the following line

mainClassName = 'Main_File'

If you're using Spring Boot, this might be the issue: https://github.com/gradle/gradle/issues/2489.

Basically, the output directories changed in Gradle 4.0, so if you have them hardcoded the execution will fail.

The solution is to replace:

bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files("$buildDir/classes/main", "$buildDir/resources/main", pathingJar.archivePath)
   }
}

by:

bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files(sourceSets.main.output.files, pathingJar.archivePath)
   }
}

I resolved it by adding below code to my application.

// enter code here this is error I was getting when I run build.gradle. main class name has not been configured and it could not be resolved

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

I fixed this by running a clean of by gradle build (or delete the gradle build folder mannually)

This occurs if you move the main class to a new package and the old main class is still referenced in the claspath


Modify build.gradle to put your main class in the manifest:

jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version,
                   'Main-Class': 'hello.helloWorld'
    }
}

Struggled with the same problem for some time. But after creating the directory structure src/main/java and putting the source(from the top of the package), it worked as expected.

The tutorial I tried with. After you execute gradle build, you will have to be able to find classes under build directory.


In my build.gradle, I resolved this issue by creating a task and then specifying the "mainClassName" as follows:

task(runSimpleXYZProgram, group: 'algorithms', description: 'Description of what your program does', dependsOn: 'classes', type: JavaExec) {
    mainClassName = 'your.entire.package.classContainingYourMainMethod'
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK