Skip to content

Instantly share code, notes, and snippets.

@ghostbear
Last active December 27, 2023 06:36
Show Gist options
  • Save ghostbear/b0aa3bf1a323b38be98bb1a66db65b41 to your computer and use it in GitHub Desktop.
Save ghostbear/b0aa3bf1a323b38be98bb1a66db65b41 to your computer and use it in GitHub Desktop.

Bazel - How to add a newer version of Java

First find a JDK you want to use in Bazel, I will use Azul Zulu JDK 21 EA.

image

From the JDK vendor you choose you will need to find the download url and SHA256. In my case I find the download url by right clicking .zip and selecting Copy link address, and for the SHA256 I click the Checksum (SHA256) and copy the SHA256.

Now in your WORKFILE add the following

load("@bazel_tools//tools/jdk:remote_java_repository.bzl", "remote_java_repository")

remote_java_repository(
    name = "name_for_the_java_repository",
    prefix = "zulujdk",
    sha256 = "bbc8c786c2ed41bf8471f2829854b5f78a24d20195c4a69a6c529c1e81cd8be7", # The SHA256 you copied goes here
    strip_prefix = "zulu21.0.21-ea-jdk21.0.0-ea.6-win_x64", # The file name of the downloaded file
    target_compatible_with = ["@platforms//os:windows"], # Or @platforms//os:mac, @platforms//os:linux depending on which JDK you are downloading
    urls = ["https://cdn.azul.com/zulu/bin/zulu21.0.21-ea-jdk21.0.0-ea.6-win_x64.zip"], # The download url you copied goes here
    version = "21", # Replace with the Java version you are downloading
)

And in your BUILD file add the following

load(
    "@bazel_tools//tools/jdk:default_java_toolchain.bzl",
    "BASE_JDK9_JVM_OPTS",
    "DEFAULT_JAVACOPTS",
    "DEFAULT_TOOLCHAIN_CONFIGURATION",
    "default_java_toolchain",
)

default_java_toolchain(
    name = "name_for_the_java_toolchain",
    configuration = DEFAULT_TOOLCHAIN_CONFIGURATION,
    java_runtime = "@name_for_the_java_repository//:jdk",
    javacopts = DEFAULT_JAVACOPTS + ["--enable-preview"],
    jvm_opts = BASE_JDK9_JVM_OPTS + ["--enable-preview"],
    source_version = "21",
    target_version = "21",
)

# More rules
# java_binary(

Finally in the .bazelrc add the following

build --extra_toolchains=//:name_for_the_java_toolchain_definition
build --java_language_version=21
build --java_runtime_version=21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment