Gradle Compile & Execute the Single Java Class with third-party jar dependencies using Gradle `buildscript`

Tags: , ,



I followed this answer https://stackoverflow.com/a/19418847/1665592 but it doesn’t help me to compile single java files using Gradle. It says Task :compileMessageKeys NO-SOURCE Why?

I just have only one Java File CreateMessageKeysTask.java which is dependent on "apache-ant-1.7.0/ant.jar" jar

task compileMessageKeys (type: JavaCompile) {
    doFirst {
        println "$projectDir/precompile"
        new File("$projectDir/precompile").mkdirs()
    }
    source = sourceSets.main.java.srcDirs
    include 'mypackage.build.CreateMessageKeysTask.java'
    classpath = sourceSets.main.compileClasspath
    destinationDir = sourceSets.main.output.classesDir
}

compileMessageKeys.options.compilerArgs = ["-sourcepath", "builder/precompile-task/src/mypackage/build"]

My ant script is as below

  <target name="precompile"
          description="builds the CreateMessageKeysTask to generates the MessageKeys interface">
    <mkdir dir="${precompile}" />
    <echo message=" precompile.src: ${precompile.src}" />
    <javac srcdir="${precompile.src}" destdir="${precompile}"
           includes="mypackage/build/**"
           debug="true" fork="true" memoryMaximumSize="${javacCoreMaxMem}"
           includeantruntime="false">
      <classpath>
        <fileset dir="${my.proj.base}/lib/">
          <include name="apache-ant-1.7.0/ant.jar" />
        </fileset>
      </classpath>
    </javac>
  </target>

Below are the class import statements used in my Java File.

import org.apache.tools.ant.*

import java.io.*;
import java.util.*;

EDIT

I tried something below as well but it still not help me

task compileMessageKeys (type: JavaCompile) {
    doFirst {
        println "$projectDir/precompile"
        new File("$projectDir/precompile").mkdirs()
    }
    dependencies{
        compile fileTree(dir: 'lib/', include: ['apache-ant-1.7.0/ant.jar'])
    }
    source = sourceSets.main.java.srcDirs
    include 'mypackage.build.CreateMessageKeysTask.java'
    classpath = sourceSets.main.compileClasspath
    destinationDir = sourceSets.main.output.classesDir
}

Answer

It is pretty simple in to compile and execute java code in Gradle with buildscript

buildscript {
    dependencies {
        classpath files('lib/apache-ant-1.7.0/ant.jar')
    }
}


task CreateMessageKeys {
    def obj = new mypackage.build.CreateMessageKeysTask();
    obj.execute();
}


Source: stackoverflow