Skip to content

Checkstyle 代码检查

Checkstyle 是一个静态代码分析工具,用于检查 Java 代码是否符合编码规范。

基本配置

kotlin
plugins {
    java
    checkstyle
}

checkstyle {
    toolVersion = "10.12.5"
    configFile = file("config/checkstyle/checkstyle.xml")
    maxWarnings = 0    // 警告数量超过此值则失败
    maxErrors = 0      // 错误数量超过此值则失败
    isIgnoreFailures = false
}

Checkstyle 规则文件

xml
<!-- config/checkstyle/checkstyle.xml -->
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
    "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
    "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <property name="charset" value="UTF-8"/>
    <property name="severity" value="warning"/>
    
    <!-- 文件长度 -->
    <module name="FileLength">
        <property name="max" value="500"/>
    </module>
    
    <module name="TreeWalker">
        <!-- 命名规范 -->
        <module name="TypeName"/>
        <module name="MethodName"/>
        <module name="ConstantName"/>
        
        <!-- 导入 -->
        <module name="AvoidStarImport"/>
        <module name="UnusedImports"/>
        
        <!-- 代码格式 -->
        <module name="LineLength">
            <property name="max" value="120"/>
        </module>
        <module name="WhitespaceAround"/>
        
        <!-- Javadoc(可选) -->
        <!-- <module name="JavadocMethod"/> -->
    </module>
</module>

运行检查

bash
# 检查所有源码
./gradlew checkstyleMain
./gradlew checkstyleTest

# 随 build 一起运行(check 任务包含 checkstyle)
./gradlew check

# 查看报告
# build/reports/checkstyle/main.html

跳过 Checkstyle

bash
# 跳过 Checkstyle
./gradlew build -x checkstyleMain -x checkstyleTest
kotlin
// 特定任务中跳过
tasks.named("checkstyleTest") {
    enabled = false
}

使用 Google Java Style

kotlin
dependencies {
    checkstyle("com.puppycrawl.tools:checkstyle:10.12.5")
}

Google Java Style Guide 中下载 google_checks.xml,或:

xml
<!-- checkstyle.xml 使用 Google 规则 -->
<!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
    "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
    <module name="SuppressionFilter">
        <property name="file" value="${checkstyle.suppressions.file}" default=""/>
    </module>
</module>

下一步