Java 代码规范

文章内容
  1. Checkstyle
  2. PMD

Java 常用代码规范检查工具如下:

工具 lint 命令 支持 IDE
Checkstyle ./gradlew check VSCodeIDEA
PMD ./gradlew check VSCodeIDEA
P3C-PMD ./gradlew check VSCodeIDEA

Checkstyle

Checkstyle 内置 2 种规范——Google 与 Sun,其中常用的「Google Java Style」规范包括下列规则:

  • 每行代码最大长度 100 个字符;
  • 缩进使用 2 个空格;

安装

本文以 Checkstyle Gradle Plugin 为例,而 Maven 老项目可使用命令一键升级到 Gradle:

gradle init --type pom

修改 build.gradle

plugins {
    id 'checkstyle'
}
checkstyle {
    toolVersion = '8.39'
    maxWarnings = 0
    maxErrors = 0
}

下载代码规范 XML 文件,保存到项目中:

wget https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-8.39/src/main/resources/google_checks.xml -O config/checkstyle/checkstyle.xml

全量检查

$ ./gradlew check

[WARN] TaskTest.java:543: 本行字符数 101个,最多:100个。 [LineLength]
[WARN] ReportTest.java:206:9: 第 9 个字符 '}'应该与下一部分位于同一行。
[WARN] ProjectRoleTest.java:449:8: 注释应缩进8个缩进符,而不是7个。

增量检查

修改 build.gradle

plugins {
    id 'checkstyle'
}
checkstyle {
    toolVersion = '8.39'
    maxWarnings = 0
    maxErrors = 0
}

task checkstyleChanged(type: Checkstyle) {
    source "${project.rootDir}"
    def changedFiles = getChangedFiles()
    if (changedFiles) {
        // include changed files only
        include changedFiles
    } else {
        // if no changed Java files detected, exclude all
        exclude "**/*"
    }
    classpath = files()
    showViolations = true

    // Define the output folder for the generated reports
    def reportsPath = "${buildDir}/reports/checkstyle"
    reports {
        html.enabled true
        html.destination rootProject.file("${reportsPath}/changed-files.html")

        xml.enabled true
        xml.destination rootProject.file("${reportsPath}/changed-files.xml")
    }
}

static def getChangedFiles() {
    ByteArrayOutputStream systemOutStream = new ByteArrayOutputStream()
    def diffFile = ''
    def files = []

    try {
        diffFile = new FileInputStream(".diff").getText();
    } catch (FileNotFoundException e) {
        ("git diff --name-only --diff-filter=d HEAD").execute().waitForProcessOutput(systemOutStream, System.err)
        diffFile = systemOutStream.toString()
        systemOutStream.close()
    }

    // Collect only *.java-files from all changed files
    for (file in diffFile.trim().split('\n')) {
        if (file.endsWith(".java")) {
            files.add(file)
        }
    }
    return files
}

本地运行:

./gradlew checkstyleChanged

持续集成合并请求时运行:

pipeline {
  agent any
  stages {
    stage('检出') {
      steps {
        checkout([
          $class: 'GitSCM',
          branches: [[name: '*']],
          userRemoteConfigs: [[url: env.GIT_REPO_URL, credentialsId: env.CREDENTIALS_ID]]
        ])
        script {
          sh 'touch .diff'
          if (env.MR_SOURCE_BRANCH ==~ /.*/) {
            sh "git checkout ${env.MR_TARGET_BRANCH}"
            sh "git checkout ${env.MR_SOURCE_BRANCH}"
            sh "git diff --diff-filter=d --name-only ${env.MR_TARGET_BRANCH}... > .diff"
          } else {
            sh "git checkout ${env.GIT_COMMIT}"
          }
        }
      }
    }
    stage('增量检查代码规范') {
      when {
        changeRequest()
      }
      agent {
        docker {
          image 'adoptopenjdk:11-jdk-hotspot'
          args '-v /root/.gradle/:/root/.gradle/ -v /root/.m2/:/root/.m2/'
          reuseNode true
        }
      }
      steps {
        sh './gradlew checkstyleChanged'
      }
    }
  }
}

PMD

PMD maven 包中内置了 xml 规则文件,安装即可使用,无需单独下载 xml,也可以自定义规则,比如「阿里巴巴 Java 规范」。

安装

本文以 PMD Gradle Plugin 为例,而 Maven 老项目可使用命令一键升级到 Gradle:

gradle init --type pom

此处以 Gradle 6.8.3 为例,老版本的 Gradle 可能报错,请先升级,修改 gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-6.8.3-bin.zip

修改 build.gradle

plugins {
    id 'pmd'
}
pmd {
    consoleOutput = true
    rulesMinimumPriority = 5
    // 官方规范列表(无需下载) https://github.com/pmd/pmd/tree/master/pmd-java/src/main/resources/category/java
    // ruleSets = ["category/java/codestyle.xml", "category/java/bestpractices.xml"]
    // 阿里规范列表(无需下载) https://github.com/alibaba/p3c/tree/master/p3c-pmd/src/main/resources/rulesets/java
    ruleSets = [
        "rulesets/java/ali-comment.xml",
        "rulesets/java/ali-concurrent.xml",
        "rulesets/java/ali-constant.xml",
        "rulesets/java/ali-exception.xml",
        "rulesets/java/ali-flowcontrol.xml",
        "rulesets/java/ali-naming.xml",
        "rulesets/java/ali-oop.xml",
        "rulesets/java/ali-orm.xml",
        "rulesets/java/ali-other.xml",
        "rulesets/java/ali-set.xml"
    ]
}

dependencies {
  // 版本号来自 https://mvnrepository.com/artifact/com.alibaba.p3c/p3c-pmd
  pmd 'com.alibaba.p3c:p3c-pmd:2.1.1'
}

全量检查

$ ./gradlew check

> Task :pmdMain FAILED
DemoApplication.java:7: 【DemoApplication】缺少包含@author的注释信息
DemoApplication.java:9: 请不要使用行尾注释

上一篇PHP 代码规范
最近更新
感谢反馈有用
感谢反馈没用

在阅读中是否遇到以下问题?

您希望我们如何改进?