Search code examples
javabazel

How to resolve the java_toolchain in bazel


Bazel discusses how to create java toolchains, e.g.

java_toolchain(
  name = "my_toolchain",
  encoding = "UTF-8",
  source_version = "8",
  target_version = "8",
  misc = [
    "-extra_checks:on",
  ],
)

from a blog post on configuring java builds. But, how can resolve the java toolchain from a rule?

java_toolchain = ctx.toolchains["@bazel_tools//<something here>"]

I expect something like the above, but I could not find documentation on the bazel java rules documentation page.


Solution

  • You are right, this would be the preferred way to access the Java toolchain. Unfortunately, the Java rules do not currently support toolchain resolution, so this isn't possible, and the Java toolchain will need to be accessed via a private attribute that depends on @bazel_tools//tools/jdk:current_java_toolchain. See the default_javacopts rule for an example.

    There is work starting soon to address this, and we'll be sure to announce to the community when Java rules support toolchain resolution and this works the way you expect.