Return value from java process in gradle task

Is it possible to return a value from a class executed by the gradle javaExec task? I have:

task myTask(dependsOn: classes) << {
    javaexec {
      classpath = sourceSets.test.runtimeClasspath
      main = 'com.samples.MyClass'
      args=["test"]
    }
         // Continue using the value from the MyClass there!
        }

And where the MyClass is:

public class MyClass {
  public static void main(String[] args) {
    List<String> result = new ArrayList<String>();
    result.add("v0");
    result.add("v1");
    result.add("v2");
          String buildString = "";
    for (String string : result) {
      buildString+=string;
    }
    System.out.println(buildString);
      }

Direct answer to your question… You’ll need access to what’s written to the output stream. I think something like this would work:

task myTask(dependsOn: classes) << {
  def os = new ByteArrayOutputStream()
      javaexec {
    classpath = sourceSets.test.runtimeClasspath
    main = 'com.samples.MyClass'
    args=["test"]
    standardOutput = os
  }
  def buildString = os.toString()
  // Continue using the value from the MyClass there!
}

On the other hand, you could just directly use ‘MyClass’ as part of the build. That would avoid the extra overhead of a separate task. If you put that class into a plugin JAR, or into ‘buildSrc’, or even just declare it directly in the ‘build.gradle’, it would just be on the build’s classpath.