gradlegroovy

where does mainClass variable come from in gradle?


plugins {
id 'java'
id 'application'
}
application {
mainClass = "org.example.Main"
}
group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
mavenCentral()
}

dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation project(":api")
}

test {
useJUnitPlatform()
}

nothing wrong with the code but I know that all already defined variables come from the Project Object

the mainClass variable is from plugin application but why is that I can only assign the variable in applications block and not anywhere else? what class is this variable from?


Solution

  • mainClass is not a variable in this case. mainClass is a property on the application extension which is contributed to the project through the Application Plugin

    When you do:

    application {
    
    }
    

    This is actually the Groovy DSL (or Kotlin DSL) at work which can be thought of as syntactic sugar over the underlying APIs provided by Gradle. For example, in a pure Java plugin:

    project.getExtensions().configure(JavaApplication.class, application -> {
        application.getMainClass().set("org.example.Main")
    })