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

如何在Maven配置中排除Jacoco分析的特定方法?

在Maven中配置Jacoco排除特定方法

Jacoco默认的<excludes>配置仅支持类/目录级别的排除,没法直接通过**/*.equals这类写法排除方法。要实现方法级别的静态排除,无需使用@Generated注解,有两种可行方案:

方案一:插桩阶段直接忽略方法(推荐)

在prepare-agent阶段通过Jacoco代理参数,让字节码插桩时直接跳过指定方法,这类方法不会被计入覆盖率统计:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.11</version>
    <executions>
        <execution>
            <id>prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            <configuration>
                <agent>
                    <!-- 排除所有类的equals方法 -->
                    <exclclassmethod>*:equals(*)</exclclassmethod>
                    <!-- 排除所有类中以get开头的方法(支持任意参数) -->
                    <exclclassmethod>*:get*(*)</exclclassmethod>
                </agent>
            </configuration>
        </execution>
        <execution>
            <id>report</id>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

exclclassmethod的语法规则:

  • 格式为[类匹配模式]:[方法匹配模式(含参数)]
  • *匹配任意字符序列,?匹配单个字符
  • 例如com/example/service/*:set*()会排除com.example.service包下所有类的无参set方法

方案二:报告生成阶段过滤方法

如果不想修改插桩阶段的统计逻辑,仅在生成报告时隐藏特定方法,可以使用Jacoco 0.8.7及以上版本支持的methodExcludes配置:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.11</version>
    <executions>
        <!-- 保留prepare-agent阶段原有配置(如果需要) -->
        <execution>
            <id>report</id>
            <goals>
                <goal>report</goal>
            </goals>
            <configuration>
                <methodExcludes>
                    <methodExclude>*:equals(*)</methodExclude>
                    <methodExclude>*:get*(*)</methodExclude>
                </methodExcludes>
            </configuration>
        </execution>
    </executions>
</plugin>

这种方式下,插桩时仍会统计目标方法的覆盖率,但最终报告中不会展示这些方法的统计结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:40:17