How to specify Java version with Bazel

Viewed 3700

I am using Bazel to build and test a Java project. It seems to be compiling with JDK10 that it downloaded from somewhere. Would like to specify that it use JDK13.

How do I do this? is it something i can put in the .bazelrc or BUILD file? Really having trouble with this.

3 Answers

Bazel comes with some toolchains already defined, and they can specified on the command line or in your .bazlrc:

build --java_toolchain=@bazel_tools//tools/jdk:toolchain_java11 --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_java11

Unfortunately no standard JDK13 toolchain yet..

java_toolchain seems to do the trick:

For example:

In your BUILD file add:

java_toolchain(
    name = "bootstrap_toolchain",
    # javac -extdirs is implemented by appending the contents to the platform
    # class path after -bootclasspath. For convenience, we currently have a
    # single jar that contains the contents of both the bootclasspath and
    # extdirs.
    bootclasspath = ["//tools/jdk:platformclasspath.jar"],
    extclasspath = [],
    genclass = ["bootstrap_genclass_deploy.jar"],
    ijar = ["//third_party/ijar"],
    javabuilder = ["bootstrap_VanillaJavaBuilder_deploy.jar"],
    javac = ["//third_party/java/jdk/langtools:javac_jar"],
    jvm_opts = [
        # Prevent "Could not reserve enough space for object heap" errors on Windows.
        "-Xmx512m",
        # Using tiered compilation improves performance of Javac when not using the worker mode.
        "-XX:+TieredCompilation",
        "-XX:TieredStopAtLevel=1",
    ],
    singlejar = ["//src/java_tools/singlejar:bootstrap_deploy.jar"],
    source_version = "8",
    tags = ["manual"],
    target_version = "8",
    visibility = ["//visibility:public"],
)

.bazelrc

build --java_toolchain=//:bootstrap_toolchain

You can now Configure the JDK Toolchain to use a locally installed JDK.

After installing OpenJDK 16, I created ~/.bazelrc with the following contents:

build --define=ABSOLUTE_JAVABASE=/home/guaporocco/.jdks/openjdk-16
build --javabase=@bazel_tools//tools/jdk:absolute_javabase
build --host_javabase=@bazel_tools//tools/jdk:absolute_javabase
build --java_toolchain=@bazel_tools//tools/jdk:toolchain_vanilla
build --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_vanilla

I can confirm that this works with test projects using features introduced after version 11, like multi-line-strings.

Related