Problem with JavaExec and execution phase

Hi!

Thank you for taking a moment to look at my question. I replicated my problem in a very small Gradle build file:

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

defaultTasks = ['COMPILE_AND_RUN']

mainClassName = "TestClassToExecute" // in the default package
sourceSets.main.java.srcDirs = ["./main/java"]
sourceSets.main.resources.srcDirs = ["./main/resources"]

task COMPILE_AND_RUN(type: JavaExec) << {
	main = mainClassName
	classpath sourceSets.main.runtimeClasspath
	classpath configurations.runtime
}

And then I get the following error:

Execution failed for task ':COMPILE_AND_RUN'.
> No main class specified

Any ideas? I initially had the COMPILE_AND_RUN task in the configuration phase (without <<) and everything worked fine. But then when I wanted to execute other tasks (eg distZip from the ‘application’ plugin), then it would still execute the COMPILE_AND_RUN task as it was defined to be executed in the configuration phase. Subsequently I moved the COMPILE_AND_RUN task to the execution phase, but now I’m getting this “No main class specified” error…

What am I missing here? Thank you! :slight_smile:

When you define your COMPILE_AND_RUN task, if you use ‘<<’ you basically declare a ‘doLast’ action on the task.
This is not what you want to do :
You want to configure the JavaExec task you’re creating, by specifying the main attribute and calling (twice) the classpath method.
So writing

task COMPILE_AND_RUN(type: JavaExec) {
main = mainClassName
classpath sourceSets.main.runtimeClasspath
classpath configurations.runtime
}

without the << shall solve your problem.

To clarify my answer:
By looking at the javaexec code and especially the @TaskAction method call hierarchy , the exception is voluntarily thrown when the main class attribute is not set.
Since you set it during the doLast action of the task, the exception is thrown when the regular action is executed.
What do you want to achieve exactly, regarding the distZip task? In the end, what tasks do you want to be executed? Why the compile and run task should not be executed when the distZip task is called?