mcpField
J
java-quality

java-quality

github.com/claude-dev-suite测试与质量4660 次安装2 天前更新
代码仓库

关于 java-quality

java-quality 是一份使用静态分析工具改善 Java 代码质量的参考技能,面向 Java 开发者。内容涵盖工具配置、常见问题处理,以及在 Maven 和 CI 中组合检查。

主要功能

  1. 01Checkstyle、SpotBugs、PMD 等工具配置
  2. 02Maven 与 Gradle 集成示例
  3. 03常见代码异味及修复建议
  4. 04组合质量检查配置
  5. 05CI 质量检查实践

适用场景

  1. 01为 Java 项目添加静态分析
  2. 02排查 SpotBugs 警告和误报
  3. 03将质量检查纳入 Maven 构建
  4. 04识别复杂度和代码异味

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill java-quality

安装后在 Claude Code 中输入/java-quality确认已加载。

详细介绍

Java 质量 - 快速参考

何时不使用此技能

  • SonarQube 通用设置 - 使用 sonarqube 技能
  • Spring Boot 测试 - 使用 Spring Boot 测试技能
  • 安全扫描 - 使用 java-security 技能
  • 覆盖率报告 - 使用 jacoco 技能

深入了解:使用 mcp__documentation__fetch_docs,并将 technology 设为 spring-boot,以获取框架专属模式。

工具概览

工具侧重点速度集成方式
Checkstyle代码风格、格式快Maven/Gradle
SpotBugsBug 模式、字节码中Maven/Gradle
PMD代码异味、复杂度快Maven/Gradle
SonarJava一站式慢SonarQube
Error Prone编译时错误快编译器插件

Checkstyle 设置

Maven 配置

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-checkstyle-plugin</artifactId>
    <version>3.3.1</version>
    <configuration>
        <configLocation>checkstyle.xml</configLocation>
        <consoleOutput>true</consoleOutput>
        <failsOnError>true</failsOnError>
        <violationSeverity>warning</violationSeverity>
    </configuration>
    <executions>
        <execution>
            <id>validate</id>
            <phase>validate</phase>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.puppycrawl.tools</groupId>
            <artifactId>checkstyle</artifactId>
            <version>10.12.5</version>
        </dependency>
    </dependencies>
</plugin>
checkstyle.xml(基于 Google 风格)
<?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="severity" value="warning"/>
    <property name="fileExtensions" value="java"/>

    <module name="TreeWalker">
        
        <module name="ConstantName"/>
        <module name="LocalVariableName"/>
        <module name="MemberName"/>
        <module name="MethodName"/>
        <module name="PackageName"/>
        <module name="ParameterName"/>
        <module name="TypeName"/>

        
        <module name="IllegalImport"/>
        <module name="RedundantImport"/>
        <module name="UnusedImports"/>

        
        <module name="LineLength">
            <property name="max" value="120"/>
        </module>
        <module name="MethodLength">
            <property name="max" value="50"/>
        </module>
        <module name="ParameterNumber">
            <property name="max" value="5"/>
        </module>

        
        <module name="CyclomaticComplexity">
            <property name="max" value="10"/>
        </module>
        <module name="NPathComplexity">
            <property name="max" value="200"/>
        </module>

        
        <module name="EmptyBlock"/>
        <module name="EqualsHashCode"/>
        <module name="HiddenField"/>
        <module name="MissingSwitchDefault"/>
        <module name="SimplifyBooleanExpression"/>
        <module name="SimplifyBooleanReturn"/>
    </module>

    
    <module name="FileLength">
        <property name="max" value="500"/>
    </module>
    <module name="NewlineAtEndOfFile"/>
</module>
命令
# Run Checkstyle
./mvnw checkstyle:check

# Generate report
./mvnw checkstyle:checkstyle

SpotBugs 设置

Maven 配置

<plugin>
    <groupId>com.github.spotbugs</groupId>
    <artifactId>spotbugs-maven-plugin</artifactId>
    <version>4.8.3.0</version>
    <configuration>
        <effort>Max</effort>
        <threshold>Medium</threshold>
        <failOnError>true</failOnError>
        <plugins>
            <plugin>
                <groupId>com.h3xstream.findsecbugs</groupId>
                <artifactId>findsecbugs-plugin</artifactId>
                <version>1.12.0</version>
            </plugin>
        </plugins>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>
排除误报

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
    
    <Match>
        <Package name="~.*\.generated\..*"/>
    </Match>

    
    <Match>
        <Bug pattern="EI_EXPOSE_REP"/>
        <Class name="~.*Dto"/>
    </Match>
</FindBugsFilter>
命令
# Run SpotBugs
./mvnw spotbugs:check

# Generate report
./mvnw spotbugs:spotbugs

# GUI viewer
./mvnw spotbugs:gui
常见 SpotBugs 警告
Bug ID描述修复方法
NP_NULL_ON_SOME_PATH可能存在空值解引用添加空值检查或使用 Optional
EI_EXPOSE_REP返回可变对象返回防御性副本
MS_SHOULD_BE_FINAL静态字段应为 final添加 final 修饰符
SQL_INJECTIONSQL 注入风险使用参数化查询
DM_DEFAULT_ENCODING使用默认编码显式指定字符集

PMD 设置

Maven 配置

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-pmd-plugin</artifactId>
    <version>3.21.2</version>
    <configuration>
        <rulesets>
            <ruleset>pmd-rules.xml</ruleset>
        </rulesets>
        <failOnViolation>true</failOnViolation>
        <printFailingErrors>true</printFailingErrors>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>
pmd-rules.xml
<?xml version="1.0"?>
<ruleset name="Custom Rules">
    <description>Custom PMD ruleset</description>

    
    <rule ref="category/java/bestpractices.xml">
        <exclude name="JUnitTestContainsTooManyAsserts"/>
    </rule>

    
    <rule ref="category/java/codestyle.xml">
        <exclude name="AtLeastOneConstructor"/>
        <exclude name="OnlyOneReturn"/>
    </rule>

    
    <rule ref="category/java/design.xml">
        <exclude name="LawOfDemeter"/>
    </rule>

    
    <rule ref="category/java/errorprone.xml"/>

    
    <rule ref="category/java/performance.xml"/>

    
    <rule ref="category/java/design.xml/CyclomaticComplexity">
        <properties>
            <property name="methodReportLevel" value="10"/>
        </properties>
    </rule>

    <rule ref="category/java/design.xml/CognitiveComplexity">
        <properties>
            <property name="reportLevel" value="15"/>
        </properties>
    </rule>
</ruleset>
命令
# Run PMD
./mvnw pmd:check

# Generate report
./mvnw pmd:pmd

# Copy-paste detection
./mvnw pmd:cpd

Error Prone 设置

Maven 配置

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.12.1</version>
    <configuration>
        <compilerArgs>
            <arg>-XDcompilePolicy=simple</arg>
            <arg>-Xplugin:ErrorProne</arg>
        </compilerArgs>
        <annotationProcessorPaths>
            <path>
                <groupId>com.google.errorprone</groupId>
                <artifactId>error_prone_core</artifactId>
                <version>2.24.1</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

组合质量配置

一站式 Maven 配置文件

<profiles>
    <profile>
        <id>quality</id>
        <build>
            <plugins>
                
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-checkstyle-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals><goal>check</goal></goals>
                        </execution>
                    </executions>
                </plugin>

                
                <plugin>
                    <groupId>com.github.spotbugs</groupId>
                    <artifactId>spotbugs-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals><goal>check</goal></goals>
                        </execution>
                    </executions>
                </plugin>

                
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-pmd-plugin</artifactId>
                    <executions>
                        <execution>
                            <goals><goal>check</goal></goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
# Run all quality checks
./mvnw verify -Pquality

常见代码异味及修复方法

1. 上帝类
// BAD - Class does too much
public class OrderService {
    public Order createOrder() { ... }
    public void sendEmail() { ... }
    public void generatePdf() { ... }
    public void calculateTax() { ... }
    public void updateInventory() { ... }
}

// GOOD - Single responsibility
public class OrderService {
    private final EmailService emailService;
    private final PdfGenerator pdfGenerator;
    private final TaxCalculator taxCalculator;
    private final InventoryService inventoryService;

    public Order createOrder(OrderRequest request) {
        Order order = buildOrder(request);
        order.setTax(taxCalculator.calculate(order));
        inventoryService.reserve(order.getItems());
        return orderRepository.save(order);
    }
}
2. 参数列表过长
// BAD
public void createUser(String name, String email, String phone,
    String address, String city, String country, String zipCode) { }

// GOOD - Use builder or DTO
public void createUser(CreateUserRequest request) { }

@Builder
public record CreateUserRequest(
    String name,
    String email,
    String phone,
    Address address
) {}
3. 特性嫉妒
// BAD - Method uses another object's data excessively
public double calculateTotal(Order order) {
    double total = 0;
    for (OrderItem item : order.getItems()) {
        total += item.getPrice() * item.getQuantity();
        if (item.getDiscount() > 0) {
            total -= item.getPrice() * item.getQuantity() * item.getDiscount();
        }
    }
    return total;
}

// GOOD - Move logic to Order
public class Order {
    public double calculateTotal() {
        return items.stream()
            .mapToDouble(OrderItem::getSubtotal)
            .sum();
    }
}

public class OrderItem {
    public double getSubtotal() {
        double base = price * quantity;
        return discount > 0 ? base * (1 - discount) : base;
    }
}
4. 基本类型偏执
// BAD
public void sendEmail(String email) {
    if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
        throw new IllegalArgumentException("Invalid email");
    }
}

// GOOD - Value object
public record Email(String value) {
    public Email {
        if (!value.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
            throw new IllegalArgumentException("Invalid email: " + value);
        }
    }
}

public void sendEmail(Email email) { ... }
5. 嵌套过深
// BAD
public void process(Order order) {
    if (order != null) {
        if (order.isValid()) {
            for (OrderItem item : order.getItems()) {
                if (item.isAvailable()) {
                    if (item.getQuantity() > 0) {
                        // process
                    }
                }
            }
        }
    }
}

// GOOD - Guard clauses
public void process(Order order) {
    if (order == null || !order.isValid()) {
        return;
    }

    order.getItems().stream()
        .filter(OrderItem::isAvailable)
        .filter(item -> item.getQuantity() > 0)
        .forEach(this::processItem);
}

质量指标目标

指标目标工具
圈复杂度< 10Checkstyle、PMD
认知复杂度< 15PMD、SonarQube
方法长度< 50 行Checkstyle
类长度< 500 行Checkstyle
参数数量< 5Checkstyle
嵌套深度< 4PMD

CI/CD 集成

GitHub Actions
name: Quality
on: [push, pull_request]

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'
          cache: maven

      - name: Run quality checks
        run: ./mvnw verify -Pquality

      - name: Upload reports
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: quality-reports
          path: |
            target/checkstyle-result.xml
            target/spotbugsXml.xml
            target/pmd.xml

反模式

反模式不良影响正确做法
抑制所有警告掩盖真正的问题逐项修复或说明理由
CI 中不运行静态分析质量会随时间下降将其加入构建流水线
只运行 Checkstyle会遗漏 Bug 和代码异味与 SpotBugs 和 PMD 结合使用
复杂度阈值过高允许难以维护的代码将圈复杂度保持在 < 10
排除整个包忽略这些区域的代码质量精确指定排除项

快速故障排查

问题可能原因解决方案
Checkstyle 因生成的代码而失败没有排除模式为生成目录添加 <exclude>
SpotBugs 对 DTO 误报记录类型触发 EI_EXPOSE_REP为 DTO 配置排除模式
PMD 运行太慢分析了所有文件配置增量分析
Error Prone 冲突版本不匹配与 JDK 版本保持一致
CI 中质量门禁失败本地配置不同提交配置文件

相关技能

评论

支持 Markdown