Checkstyle is a static analysis tool that can check Java code against a set of style rules.
Given below are some instructions on how to use Checkstyle for some common project tasks.
Checkstyle expects configuration files for checkstyle (e.g., files that specify which style rules to follow) to be in ./config/checkstyle/
by convention.
The set of code style rules are put in the config/checkstyle/checkstyle.xml
. To enable exceptions to code styles, you can add in the comment //CODESTYLE.OFF: RuleName
at the start of the section and //CODESTYLE.ON: RuleName
at the end of the section. Alternatively, you can specify which rules to suppress in a config file config/checkstyle/suppressions.xml
Checkstyle configuration matching our Java coding standard can be found in the AddressBook Level 3 project.
Here is an example of relevant lines that should be in the build.gradle
file.
plugins {
id 'checkstyle'
// other plugins
}
checkstyle {
toolVersion = '8.29'
}
Some relevant Gradle tasks added by the CheckStyle plugin.
checkstyleMain
: checks if the main code complies with the style rulescheckstyleTest
: checks if the test code complies with the style rulesFor example, you can run gradlew checkstyleMain checkstyleTest
to verify that all your code complies with the style rules.
Given below are the steps to install the Checkstyle-IDEA plugin so that Intellij can alert you about code style problems as you write code.
Install the Checkstyle-IDEA plugin as follows:
File
> Settings
(Windows/Linux), or IntelliJ IDEA
> Preferences…
(macOS)Plugins
(on the left slide menu in the dialog that pops up)Marketplace
(on to top center of the same dialog box)Click File
> Settings…
> Tools
> Checkstyle
Set Scan Scope
to Only Java sources (including tests)
, so that the plugin will run checkstyle for our test source codes as well
Ensure that the Checkstyle version
is set to the one used by the project.
If your project uses Gradle, you can check the build.gradle
file to find the correct version.
Click the +
sign under Configuration File
Enter an arbitrary description e.g. addressbook
Select Use a local Checkstyle file
Use the checkstyle configuration file found at config/checkstyle/checkstyle.xml
Click Next
> Finish
Click OK
To verify the plugin is set up correctly, temporarily modify the code to violate a style rule (e.g., add an extra line break before an {
) and run the Checkstyle check using the plugin.
Problem: When importing checkstyle.xml
, Checkstyle-IDEA plugin complains that The Checkstyle rules file could not be parsed. … The file has been blacklisted for 60s.
checkstyle.xml
is written for a particular version, but the plugin was not configured to the correct version.Checkstyle version
that matches the version in build.gradle
and have clicked
Apply
, as checkstyle.xml
is written for Gradle’s checkstyle.Problem: After setting up checkstyle.xml
, Checkstyle-IDEA plugin does not seem to highlight the errors / real-time scanning seems broken.