Bazel构建冲突:var关键字与com.sun.tools.javac引用互斥问题
问题:Java版本与
com.sun.tools.javac引用的冲突问题 简要说明
使用默认Java语言版本时,var关键字会引发错误;但指定版本11后,com.sun.tools.javac.*的引用又会报错。已制作最小复现示例。
详细说明
环境版本
- 操作系统:Windows 10
- Bazel:7.1.1(通过Bazelisk 1.19.0运行)
背景
最近迁移到bzlmod,完成本地注册表基础配置,尝试开发自定义errorprone BugChecker,需要扩展注册表的errorprone模块,除注解外还要包含check_api目录树。
核心冲突
解决其他依赖问题后,遇到无法解决的矛盾:该目录下的代码既引用com.sun.tools.javac.*又使用var关键字。
- 不指定Java版本时:默认版本为8,
var关键字触发如下错误:
warning: as of release 10, 'var' is a restricted type name \ and cannot be used for type declarations or as the element type of an array
- 指定Java 11版本时:在
.bazelrc中添加build --java_language_version=11 --tool_java_language_version=11后,com.sun.tools.javac的引用触发如下错误:
error: package com.sun.tools.javac.code is not visible import com.sun.tools.javac.code.Symbol.ClassSymbol; ^ (package com.sun.tools.javac.code is declared in module jdk.compiler, which does not export it to the unnamed module)
更令人困惑的是,Bazel显示的完整编译命令已包含多个--add-exports参数,例如:
external\rules_java~~toolchains~remotejdk21_win\bin\java.exe \ --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \ --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED \ ... (剩余19个参数已省略)
这些参数看似正是解决模块导出问题所需的配置。
需求与顾虑
- 对Java工具链配置了解有限,若必须配置,希望能集中统一设置,因为有多工作区,不想逐个单独配置。
- 部分项目最终将基于Android,工具链变更最好不要影响Android项目。
- 自定义errorprone检查仅通过Bazel的errorprone集成运行,或许只需为这些检查(及其测试)单独配置工具链?但仍希望无需自定义工具链就能解决问题。
额外说明
尝试将语言版本设为17时,触发以下错误:
ERROR: D:/_bazel_out/sfuxpclr/external/rules_jvm_external~~maven~javax_maven/BUILD:26:11: Stamping the manifest of @@rules_jvm_external~~maven~javax_maven//:javax_annotation_javax_annotation_api failed: (Exit 1): AddJarManifestEntry.exe failed: error executing StampJarManifest command (from targ et @@rules_jvm_external~~maven~javax_maven//:javax_annotation_javax_annotation_api) bazel-out\x64_windows-opt-exec-ST-13d3ddad9198\bin\external\rules_jvm_external~\private\tools\java\com\github\bazelbuild\rules_jvm_external\jar\AddJarManifestEntry.exe --source ... (剩余5个参数已省略) Error: LinkageError occurred while loading main class com.github.bazelbuild.rules_jvm_external.jar.AddJarManifestEntry java.lang.UnsupportedClassVersionError: com/github/bazelbuild/rules_jvm_external/jar/AddJarManifestEntry has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0
错误信息显示当前Java运行时版本较旧(仅支持到class文件版本55.0,对应Java 11),但代码是用Java 17(class文件版本61.0)编译的。已指定(tool_)java_language_version=17,不清楚这个旧运行时来自哪里、是什么在使用它。
内容的提问来源于stack exchange,提问作者Ben Leitner
相关产品推荐
相关产品推荐

