我正在使用Bazel作为Java项目的构建工具。我的Mac上安装了JDK 11,但是Bazel使用Java 8来构建二进制文件。有谁知道我该如何改变?

最佳答案

BUILD.bazel

java_binary(
    name = 'JavaBinary',
    srcs = ['JavaBinary.java'],
    main_class = 'JavaBinary',
)
load(
    "@bazel_tools//tools/jdk:default_java_toolchain.bzl",
    "default_java_toolchain",
)
default_java_toolchain(
  name = "default_toolchain",
  visibility = ["//visibility:public"],
)


JavaBinary.java

public class JavaBinary {
   public static void main(String[] args) {
    System.out.println("Successfully executed JavaBinary!");
    System.out.println("Version: " + System.getProperty("java.version"));
  }
}


WORKSPACE.bazel

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_java",
    sha256 = "220b87d8cfabd22d1c6d8e3cdb4249abd4c93dcc152e0667db061fb1b957ee68",
    url = "https://github.com/bazelbuild/rules_java/releases/download/0.1.1/rules_java-0.1.1.tar.gz",
)

load("@rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains")

rules_java_dependencies()

rules_java_toolchains()


这样运行:

bazel run :JavaBinary \
      --java_toolchain=:default_toolchain \
      --javabase=@bazel_tools//tools/jdk:remote_jdk11


您也可以创建.bazelrc文件,然后执行bazel run :JavaBinary

.bazelrc

build --java_toolchain=:default_toolchain
build --javabase=@bazel_tools//tools/jdk:remote_jdk11

07-25 23:33