Friday, March 11, 2016

Getting JDK information in Gradle to add tools.jar as dependency

Many times we would have the necessity of tools.jar into our class path at runtime. Mostly when you do something with compile or javadoc.
The best way which I found to do this is ask the Gradle itself to give JVM information and get tools.jar or rt.jar (runtime jar) from it.

Gradle have a singleton Class org.gradle.internal.jvm.Jvm which give the information about the JVM. The JAVA_HOME or java.home directory, runtime jar, tools jar, calling any other executable from the jdk, etc.

dependencies {
   runtime files(org.gradle.internal.jvm.Jvm.current().toolsJar)
}
Works well for Gradle project in eclipse or when running in a build street. Note that when you need tools.jar in eclipse. the Gradle work environment must be set to use JDK instead of JRE. This can be done in eclipse preferences of Gradle.
import org.gradle.internal.jvm.Jvm
println Jvm.current().javaHome
println Jvm.current().javacExecutable
println Jvm.current().javadocExecutable

You can also get other information from Jvm class. It implements interface org.gradle.internal.jvm.JavaInfo which has following outline.