【发布时间】:2021-05-12 07:48:16
【问题描述】:
问题
我为 checkstyle 创建了自己的自定义检查,它可以在命令行和 maven checkstyle 插件上运行。 但是通过 gradle checkstyle 插件,出现以下错误。
* What went wrong:
Execution failed for task ':my-project:checkstyleMain'.
> Unable to create Root Module: config {C:\Users\[path to my project]\build\tmp\resource\string8421659201972573805.txt}, classpath { ...many of classpathes. not "null" }.
只要从 checkstyle.xml 中排除自定义检查,任务就会起作用。
如何在 gradle 上进行自定义检查?
版本
- 检查样式:8.37
- maven checkstyle 插件版本:3.1.2
- gradle 版本:5.6.2
实施
- 自定义检查
public class MyCheck extends AbstractCheck {
...
- checkstyle.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<module name = "Checker">
...
<module name="TreeWalker">
...
<module name="package.to.my.check.MyCheck"/>
</module>
</module>
自定义检查类和 checkstyle.xml 被打包到名为“mycheck-module”的工件中。
- pom.xml(有效)
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.2</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.37</version>
</dependency>
<dependency>
<groupId>package.to.my.check.module</groupId>
<artifactId>mycheck-module</artifactId>
<version>[version]</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirectories>
<sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
</sourceDirectories>
<configLocation>checkstyle.xml</configLocation>
<enableFilesSummary>true</enableFilesSummary>
<maxAllowedViolations>0</maxAllowedViolations>
<violationSeverity>warning</violationSeverity>
<consoleOutput>true</consoleOutput>
<failOnViolation>
false
</failOnViolation>
<propertyExpansion>
checkstyleSuppressionConfigDir=${project.basedir}
</propertyExpansion>
</configuration>
</plugin>
- build.gradle(不起作用)
buildscript {
...
dependencies {
...
classpath 'package.to.my.check.module:mycheck-module:[version]'
}
}
...
// Set up checkstyle
apply plugin: 'checkstyle'
def checkstyleSuppressionConfigDir = file("${rootDir}/suppressCheckstyle")
checkstyle {
toolVersion = '8.37'
sourceSets = [it.sourceSets.main]
config = resources.text.fromString(getClass().getResourceAsStream('checkstyle.xml').text)
ignoreFailures = false
maxWarnings = 0
maxErrors = 0
configProperties.checkstyleSuppressionConfigDir = checkstyleSuppressionConfigDir
}
【问题讨论】:
-
从堆栈跟踪,实例化或自定义检查通过 gradle 插件失败。消息:“原因:com.puppycrawl.tools.checkstyle.api.CheckstyleException:无法实例化 'package.to.my.check.MyCheck' 类,也无法将其实例化为 null。请重新检查该类名被指定为规范名称或阅读如何配置短名称用法checkstyle.org/config.htm l#Packages。还请重新检查提供给 Checker 的 ClassLoader 是否配置正确。"
标签: java gradle build.gradle checkstyle maven-checkstyle-plugin