Checkstyle is a tool that helps programmers follow coding standards. It automates the process of checking if defined coding standards are followed. It can support any coding standards by suitable configuration. Like other tools, it can be run standalone as well as integrated with Maven.
Use the following steps to analyze code with the Maven Checkstyle plugin:
project-with-violations
).mvn checkstyle:checkstyle
[INFO] [INFO] --- maven-checkstyle-plugin:2.13:checkstyle (default-cli) @ project-with-violations --- [INFO] [INFO] There are 29 checkstyle errors. [WARNING] Unable to locate Source XRef to link to - DISABLED [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS
checkstyle-result.xml
report in the target
folder:Unlike the pmd
, checkstyle
goal of Maven, the Checkstyle plugin is not bound to any phase.
When the checkstyle
goal is run, it generates a Checkstyle site report using default rulesets and the configuration set in the plugin. It also generates a Checkstyle output file in the XML format.
The Maven Checkstyle plugin supports several configuration options to customize the rules, exclude files from being checked, and so on. Let's briefly discuss the examples that show usage of Maven Checkstyle plugin in some advanced usecases:
configuration
section of the plugin:<configuration> <checkstyleRules> <module name="Checker"> <module name="TreeWalker"> <module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> </module> </module> </module> </checkstyleRules> </configuration>
configLocation
element:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.14</version> <configuration> <configLocation>checkstyle.xml</configLocation> </configuration> </plugin>
<suppressions> <suppress checks="JavadocStyleCheck" files="GeneratedObject.java" lines="50-9999"/> <suppress checks="MagicNumberCheck" files="LegacyDatasetConvertor.java" lines="221,250-295"/> </suppressions>
As in the case of PMD, we can configure the Maven Checkstyle plugin such that it fails a build in case of errors:
project-with-violations
:<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.14</version> <executions> <execution> <id>verify-style</id> <phase>process-sources</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
mvn verify
3.141.38.121