使用 ErrorProne 检测滥用 Mutable 集合
解读
在国内互联网大厂的 Java 面试中,“不可变优先” 是 Guava 被高频追问的核心思想。面试官抛出“如何用 ErrorProne 把 Mutable 集合滥用消灭在编译期”,并不是想听你背 CheckName,而是考察三条线:
- 你是否真的在工程里吃过 Mutable 集合并发修改、意外暴露引用的亏;
- 能否把 Google 的静态分析生态(ErrorProne + Refaster)无缝接入国内 Maven/Gradle 构建体系,绕过 GFW 下载、IDEA 集成、CI 卡点;
- 对 AST 规则定制的深度:能否针对公司自己的包装类(如 CommonResult<List>)写一条 @BugPattern,做到“零误报、一键修复”。
答不到“落地”这一层,基本会被判为“只看过博客”。
知识点
- ErrorProne 插件生命周期:javac → Plugin → Scanner → BugPattern → Description → Fix。
- Guava 不可变工厂方法签名特征:Immutable.copyOf()/of() 返回类型以 com.google.common.collect.Immutable 为前缀*。
- 国内构建加速:在 .mvn/gradle 目录下配置阿里云镜像 + ErrorProne 的 net.ltgt.apt 插件,避免 dl.google.com 超时。
- 误报治理:用 @RestrictedInheritance(allowedSubtypes = …) 把 MyPageInfo 这类内部 VO 加入白名单,防止把公司分页对象误标成 Mutable。
- 一键重构:配合 Refaster 模板
MutableToImmutableTemplate,在 IDEA 的 ErrorProne 插件里按 Alt+Enter 直接替换成 ImmutableList.copyOf(),让 CR 零成本通过。
答案
- 加依赖(以 Maven 为例,Gradle 同理):
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <compilerArgs> <arg>-Xplugin:ErrorProne</arg> <arg>-XepOpt:MutableCollection:MuteForGuava=true</arg> </compilerArgs> <annotationProcessorPaths> <path> <groupId>com.google.errorprone</groupId> <artifactId>error_prone_core</artifactId> <version>2.23.0</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build> - 自定义 BugPattern,文件 MutableCollectionUsage.java:
@BugPattern( name = "MutableCollection", summary = "禁止直接返回或暴露可变集合,请使用 Guava Immutable 版本", severity = ERROR, providesFix = REQUIRES_HUMAN_ATTENTION) public class MutableCollectionUsage extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> MUTABLE_FACTORY = staticMethod() .onClassAny("java.util.Arrays", "java.util.Collections", "com.google.common.collect.Lists") .namedAnyOf("asList", "singletonList", "newArrayList"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (MUTABLE_FACTORY.matches(tree, state)) { return describeFix(tree, state); } return Description.NO_MATCH; } private Description describeFix(MethodInvocationTree tree, VisitorState state) { Fix fix = SuggestedFix.replace(tree, "ImmutableList.copyOf(" + state.getSourceForNode(tree.getArguments().get(0)) + ")"); return buildDescription(tree).addFix(fix).build(); } } - 在 CI 的
.gitlab-ci.yml里加一条 mvn clean compile -Perror-prone,一旦扫描到 Mutable 集合直接失败,MR 无法合并。 - 灰度策略:先在 common-util 模块开启,收集 7 天数据,误报率低于 0.5% 再全仓库开启,避免业务团队一次性爆炸。
拓展思考
- 如果公司仍依赖 JDK 7,ErrorProne 2.x 需要 JDK 8+ 启动编译,此时可退到 SpotBugs + fb-contrib 的 mutable-collection 检测,但规则粒度粗,需要二次过滤。
- 对于 Kotlin 混合工程,ErrorProne 只能扫描 javac 生成的 bytecode 前端,Kotlin 的 mutableListOf() 需要 detekt 规则互补,否则会出现“Java 端全绿、Kotlin 端翻车”的真空地带。
- 当接口返回 泛型嵌套结构如
Result<List<User>>时,AST 只能拿到Result<>的 raw 类型,需要结合代码上下文 type arguments 推断,否则 ImmutableList.copyOf 会触发 unchecked 警告;这时可扩展 BugChecker 的 Types#asMemberOf() 做精确匹配。 - 未来升级到 Java 21 的不可变集合(List.of/Map.of) 后,可写一条 MigrationRefaster,把 ImmutableList.copyOf → List.of,让历史代码无感迁移,持续保持技术栈年轻。