Java 代码规范
文章内容
Java 常用代码规范检查工具如下:
工具 | lint 命令 | 支持 IDE |
---|---|---|
Checkstyle | ./gradlew check | VSCode、IDEA |
PMD | pmd -d src -R rulesets.xml | VSCode |
Checkstyle
Checkstyle 内置 2 种规范——Google 与 Sun,其中常用的「Google Java Style」规范包括下列规则:
- 每行代码最大长度 100 个字符;
- 缩进使用 2 个空格;
安装:
$ vi build.gradle
plugins {
id 'checkstyle'
}
checkstyle {
toolVersion = '8.37'
maxWarnings = 0
maxErrors = 0
}
$ wget https://raw.githubusercontent.com/checkstyle/checkstyle/checkstyle-8.37/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.37'
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 {
expression { env.MR_SOURCE_BRANCH ==~ /.*/ }
}
agent {
docker {
image 'openjdk:14-jdk-alpine'
args '-v /root/.gradle/:/root/.gradle/ -v /root/.m2/:/root/.m2/'
reuseNode true
}
}
steps {
sh './gradlew checkstyleChanged'
}
}
}
}

感谢反馈有用
感谢反馈没用