如何从 java 代码 运行 gradle 任务?

How to run a gradle task from a java code?

我需要从 java 方法 运行 gradle eclipse 任务到外部 gradle 项目,是否可以使用 Gradle 工具 API ?

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.

使用 Gradle 包装器

推荐的方法是 运行 exec 并在将任务作为参数传递时调用项目包装器。此示例调用当前项目包装器并将 jar 作为参数传递:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main
{
    private static String PATH_TO_GRADLE_PROJECT = "./";
    private static String GRADLEW_EXECUTABLE = "gradlew.bat";
    private static String BLANK = " ";
    private static String GRADLE_TASK = "jar";

    public static void main(String[] args)
    {
        String command = PATH_TO_GRADLE_PROJECT + GRADLEW_EXECUTABLE + BLANK + GRADLE_TASK;
        try
        {
            Runtime.getRuntime().exec(command);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

使用 Gradle 工具 API

要在外部项目上使用 Gradle 工具 api,您只需定义 GradleConnector 对象的 属性 forProjectDirectory。 运行 对 BuildLauncher 对象调用 run() 任务。下面的例子演示了基本原理:

import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;

import java.io.File;

public class ToolingAPI
{
    private static final String GRADLE_INSTALLATION = "C:\Program Files\Gradle";
    private static final String GRADLE_PROJECT_DIRECTORY = "path_to_root_of_a_gradle_project";
    private static final String GRADLE_TASK = "help";

    private GradleConnector connector;

    public ToolingAPI(String gradleInstallationDir, String projectDir)
    {
        connector = GradleConnector.newConnector();
        connector.useInstallation(new File(gradleInstallationDir));
        connector.forProjectDirectory(new File(projectDir));
    }

    public void executeTask(String... tasks)
    {
        ProjectConnection connection = connector.connect();
        BuildLauncher build = connection.newBuild();
        build.forTasks(tasks);

        build.run();
        connection.close();
    }

    public static void main(String[] args)
    {
        ToolingAPI toolingAPI = new ToolingAPI(GRADLE_INSTALLATION, GRADLE_PROJECT_DIRECTORY);
        toolingAPI.executeTask(GRADLE_TASK);
    }
}

这种方法的缺点是执行任务时 gradle 的位置无意识。如果您在 new File("somefile") 等自定义任务中调用任何文件创建或修改方法,将引发异常。