Can't run javaexec with main class from buildSrc

I am trying to run a class from root build.gradle file with project.javaexec { } method, the class can be found in buildSrc/src/main/groovy. So the project structure looks like:

├── build.gradle
└── buildSrc
    └── src
        └── main
            └── groovy
                └── Main.groovy

The build file content:

task debug << {
 project.javaexec {
  main = "Main"
 }
}

And the buildSrc Main class content:

class Main {
 public static void main(String[] args) {
  println 'Hello from buildSrc!'
 }
}

When I call the debug task, then this error message came up: Could not find or load main class class Main

But if I call the Main.main() method on the same place (without javaexec method call), then the method is executed and the project can see the Main class…

task debug << {
 Main.main()
 }
     Hello from buildSrc!

Can you tell me please what is the possible solution? I would like to run this Main class with javaexec method…

You can put the buildSrc classes on the classpath. For a Java class, you can use:

task runJava(type: JavaExec) {
 classpath file("${rootDir}/buildSrc/build/classes/main")
 main = 'HelloJava'
}

In case of a Groovy class, it is a bit more complicated as Groovy also has to be on the classpath. Here is a sample:

configurations {
 localGroovyConf
}
  dependencies {
 localGroovyConf localGroovy()
}
  task runGroovy(type: JavaExec) {
 classpath file("${rootDir}/buildSrc/build/classes/main")
 classpath configurations.localGroovyConf
 main = 'HelloGroovy'
}

Perhaps there is a simpler solution for the latter case but this one works for me well.

1 Like