You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Checkstyle中排除双括号初始化Map的缩进检查?

解决Checkstyle对双括号初始化Map的缩进检查问题

问题场景

使用默认的google-checkstyle.xml格式时,以下双括号初始化Map的代码会触发缩进警告:

Map<String, Object> payment = new LinkedHashMap<>() {{
    put("customer_number", "123456");
}};

触发的警告信息:

'block' child has incorrect indentation level 12, expected level should be one of the following: 16, 20. (169:13) [Indentation]

Checkstyle默认期望的格式是给内部代码多缩进一级:

Map<String, Object> payment = new LinkedHashMap<>() {{
        put("customer_number", "123456");
    }};

但如果想要保留自定义的缩进格式,又不能修改全局的basicOffset配置(该配置作用于所有代码行),可以通过以下两种方式解决:

可行解决方案

方案1:用SuppressionFilter忽略特定警告

在Checkstyle的主配置文件中添加SuppressionFilter模块,指向一个抑制规则文件:

<module name="SuppressionFilter">
    <property name="file" value="suppressions.xml"/>
</module>

然后在suppressions.xml中编写规则,匹配双括号初始化的代码块,抑制其Indentation检查:

<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
        "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
        "https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
    <!-- 抑制双括号初始化代码块的缩进警告 -->
    <suppress checks="Indentation"
              regexp="new\s+\w+&lt;[^&gt;]+&gt;\(\)\s*\{\{" />
</suppressions>

方案2:调整Indentation模块的匿名内部类缩进

直接修改Indentation模块的配置,设置匿名内部类的缩进偏移为0,抵消双括号带来的额外缩进要求,同时不影响全局的basicOffset:

<module name="Indentation">
    <property name="basicOffset" value="4"/>
    <!-- 让匿名内部类的内部代码不额外缩进 -->
    <property name="anonInnerClassIndent" value="0"/>
</module>

内容的提问来源于stack exchange,提问作者membersound

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 18:12:34