Skip to content
Advertisement

How to run a gradle task from a java code?

I need to run the gradle eclipse task to an external gradle project from a java method, is it possible to do it using the Gradle Tooling API ?

Advertisement

Answer

The Gradle forum gives a nice example for doing this programmatically but since it disregards the projects individual gradle wrapper, it can’t guarantee the smooth execution of your build and even break your application. For more information why you always should rely on the gradle wrapper read here and here.

Using the Gradle wrapper

The recommended approach is to run exec and call the projects wrapper while passing the task as a parameter. This example calls the current projects wrapper and passes jar as a parameter:

JavaScript

Using the Gradle Tooling API

To use the Gradle tooling api on a external project, you simply have to define the property forProjectDirectory of your GradleConnectorobject. To run a task call run() on the BuildLauncher object. The example below demostrates the basic principle:

JavaScript

The downside of this approach is the location unawareness of gradle when executing a task. In case you call any file creation or modification method in a custom task like new File("somefile") a exception will be raised.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement