Introduction to CheckStyle – CheckStyle简介

最后修改: 2018年 3月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Checkstyle is an open source tool that checks code against a configurable set of rules.

Checkstyle是一个开源的工具,它根据可配置的规则集检查代码。

In this tutorial, we’re going to look at how to integrate Checkstyle into a Java project via Maven and by using IDE plugins.

在本教程中,我们将探讨如何通过Maven和使用IDE插件将Checkstyle集成到Java项目中。

The plugins mentioned in below sections aren’t dependent on each other and can be integrated individually in our build or IDEs. For example, the Maven plugin isn’t needed in our pom.xml to run the validations in our Eclipse IDE.

下面几节提到的插件并不相互依赖,可以单独集成到我们的构建或IDE中。例如,在我们的pom.xml中不需要Maven插件来在Eclipse IDE中运行验证。

2. Checkstyle Maven Plugin

2.Checkstyle Maven Plugin

2.1. Maven Configuration

2.1.Maven配置

To add Checkstyle to a project, we need to add the plugin in the reporting section of a pom.xml:

要将Checkstyle添加到项目中,我们需要在pom.xml的报告部分添加该插件。

<reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>3.0.0</version>
            <configuration>
                <configLocation>checkstyle.xml</configLocation>
            </configuration>
        </plugin>
    </plugins>
</reporting>

This plugin comes with two predefined checks, a Sun-style check, and a Google-style check. The default check for a project is sun_checks.xml.

这个插件带有两个预定义的检查,一个是Sun风格的检查,另一个是Google风格的检查。一个项目的默认检查是sun_checks.xml.

To use our custom configuration, we can specify our configuration file as shown in the sample above. Using this config, the plugin will now read our custom configuration instead of the default one provided.

为了使用我们的自定义配置,我们可以指定我们的配置文件,如上面的例子所示。使用这个配置,该插件现在将读取我们的自定义配置,而不是提供的默认配置。

The latest version of the plugin can be found on Maven Central.

该插件的最新版本可以在Maven Central上找到。

2.2. Report Generation

2.2.报告生成

Now that our Maven plugin is configured, we can generate a report for our code by running the mvn site command. Once the build finishes, the report is available in the target/site folder under the name checkstyle.html.

现在我们的Maven插件已经配置好了,我们可以通过运行mvn site命令为我们的代码生成一份报告。一旦构建完成,报告就可以在target/site文件夹下以checkstyle.html.的名义获得。

There are three major parts to a Checkstyle report:

Checkstyle报告有三个主要部分。

Files: This section of the report provides us with the list of files in which the violations have happened. It also shows us the counts of the violations against their severity levels. Here is how the files section of the report looks like:

文件:报告的这一部分为我们提供了发生违规的文件列表。它还向我们显示了违规行为的数量和它们的严重程度。以下是报告中的文件部分的样子。

Files

Files

Rules: This part of the report gives us an overview of the rules that were used to check for violations. It shows the category of the rules, the number of violations and the severity of those violations. Here is a sample of the report that shows the rules section:

规则:报告的这一部分给了我们一个用于检查违规行为的规则概览。它显示了规则的类别、违规的数量和这些违规的严重程度。下面是一个显示规则部分的报告样本。

Rules

规则

Details: Finally, the details section of the report provides us the details of the violations that have happened. The details provided are at line number level. Here is a sample details section of the report:

细节:最后,报告的细节部分为我们提供了已经发生的违规行为的细节。所提供的细节是在行号层面。下面是报告的细节部分的一个例子。

Details

详细信息

2.3. Build Integration

2.3.建设整合

If there’s a need to have stringent checks on the coding style, we can configure the plugin in such a way that the build fails when the code doesn’t adhere to the standards.

如果需要对编码风格进行严格的检查,我们可以对插件进行配置,当代码不符合标准时,构建失败。

We do this by adding an execution goal to our plugin definition:

我们通过在我们的插件定义中添加一个执行目标来做到这一点。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-checkstyle-plugin</artifactId>
    <version>${checkstyle-maven-plugin.version}</version>
    <configuration>
        <configLocation>checkstyle.xml</configLocation>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The configLocation attribute defines which configuration file to refer to for the validations.

configLocation属性定义了验证所要参考的配置文件。

In our case, the config file is checkstyle.xml. The goal check mentioned in the execution section asks the plugin to run in the verify phase of the build and forces a build failure when a violation of coding standards occurs.

在我们的例子中,配置文件是checkstyle.xml.执行部分提到的目标check要求该插件在构建的验证阶段运行,并在发生违反编码标准的情况下强制构建失败。

Now, if we run the mvn clean install command, it will scan the files for violations and the build will fail if any violations are found.

现在,如果我们运行mvn clean install命令,它将扫描文件是否违规,如果发现任何违规,构建将失败。

We can also run only the check goal of the plugin using mvn checkstyle:check, without configuring the execution goal. Running this step will result in a build failure as well if there are any validation errors.

我们也可以使用mvn checkstyle:check,只运行插件的check目标,而不配置执行目标。如果有任何验证错误,运行这个步骤也会导致构建失败。

3. Eclipse Plugin

3.Eclipse插件

3.1. Configurations

3.1.配置

Just like with the Maven integration, Eclipse enables us to use our custom configuration.

就像与Maven集成一样,Eclipse使我们能够使用我们的自定义配置。

To import our configuration, go to Window -> Preferences -> Checkstyle. At the Global Check Configurations section, click on New.

要导入我们的配置,进入窗口->偏好->检查风格。全球检查配置部分,点击新。

This will open up a dialogue which will provide us options to specify our custom configuration file.

这将打开一个对话,它将为我们提供指定我们的自定义配置文件的选项。

3.2. Reports Browsing

3.2.报告浏览

Now that our plugin is configured we can use it to analyze our code.

现在我们的插件已经配置好了,我们可以用它来分析我们的代码。

To check coding style for a project, right-click the project in the Eclipse Project Explorer and select CheckStyle -> Check Code with Checkstyle.

要检查一个项目的编码风格,在Eclipse Project Explorer中右击项目,并选择CheckStyle -> 用Checkstyle检查代码

The plugin will give us feedback on our Java code within the Eclipse, text editor. It will also generate the violation report for the project which is available as a view in Eclipse.

该插件将在Eclipse、文本编辑器中对我们的Java代码进行反馈。它还将生成项目的违规报告,在Eclipse中可作为视图使用。

To view to violation report, go to Window -> Show View -> Other, and search for Checkstyle. Options for Violations and Violations Chart should be displayed.

要查看违规报告,请进入窗口-> 显示视图-> 其他,并搜索Checkstyle。应显示违规行为违规图表的选项。

Selecting either option will give us a representation of violations grouped by type. Here is the violation pie chart for a sample project:

选择任何一个选项都会给我们一个按类型分组的违规行为的表示。下面是一个样本项目的违规饼图。

Pie Chart Checkstyle

Pie Chart Checkstyle

Clicking on a section of the pie chart would take us to the list of actual violations in the code.

点击饼状图的某个部分,我们将进入代码中的实际违规行为列表。

Alternatively, we can open the Problem view of Eclipse IDE and check the problems reported by the plugin.

另外,我们可以打开Eclipse IDE的Problem视图,检查插件报告的问题。

Here is a sample Problem View of Eclipse IDE:

下面是Eclipse IDE的一个问题视图样本。

Proble

Proble

Clicking on any of the warnings will take us to the code where the violation has happened.

点击任何一个警告,都会带我们到发生违规行为的代码处。

4. IntelliJ IDEA Plugin

4.IntelliJ IDEA插件

4.1. Configuration

4.1.配置

Like Eclipse, IntelliJ IDEA also enables us to use our own custom configurations with a project.

和Eclipse一样,IntelliJ IDEA也使我们能够在一个项目中使用我们自己的自定义配置。

In the IDE open Settings and search for Checkstyle. A window is shown that has the option to select our checks. Click on the + button and a window will open which will let us specify the location of the file to be used.

在IDE中打开设置,搜索Checkstyle。会出现一个窗口,其中有选择我们的检查的选项。点击+按钮,将打开一个窗口,让我们指定要使用的文件的位置。

Now, we select a configuration XML file and click Next. This will open up the previous window and show our newly added custom configuration option. We select the new configuration and click on OK to start using it in our project.

现在,我们选择一个配置的XML文件,然后点击下一步。这将打开前一个窗口,显示我们新添加的自定义配置选项。我们选择新的配置并点击确定,开始在我们的项目中使用它。

4.2. Reports Browsing

4.2.报告浏览

Now that our plugin is configured, let’s use it to check for violations. To check for violations of a particular project, go to Analyze -> Inspect Code.

现在我们的插件已经配置好了,让我们用它来检查违规。要检查一个特定项目的违规情况,请进入Analyze -> Inspect Code.

The Inspections Results will give us a view of the violations under the Checkstyle section. Here is a sample report:

检查结果将让我们看到Checkstyle部分的违规情况。以下是一份报告样本。

Checkstyle

Checkstyle

Clicking on the violations will take us to the exact lines on the file where the violations have happened.

点击违规行为将把我们带到文件上发生违规行为的确切行。

5. Custom Checkstyle Configuration

5.自定义检查风格配置

In the Maven report generation section (Section 2.2), we used a custom configuration file to perform our own coding standard checks.

在Maven报告生成部分(第2.2节),我们使用了一个自定义配置文件来进行我们自己的编码标准检查。

We have a way to create our own custom configuration XML file if we don’t want to use the packaged Google or Sun checks.

如果我们不想使用打包的Google或Sun检查,我们有办法创建自己的自定义配置XML文件

Here is the custom configuration file used for above checks:

这里是用于上述检查的自定义配置文件。

<!DOCTYPE module PUBLIC
  "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
  "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
    <module name="TreeWalker">
        <module name="AvoidStarImport">
            <property name="severity" value="warning" />
        </module>
    </module>
</module>

5.1. DOCTYPE Definition

5.1.DOCTYPE的定义

The first line of the i.e. the DOCTYPE definition is an important part of the file and it tells where to download the DTD from so that the configurations can be understood by the system.

第一行即DOCTYPE定义是文件的一个重要部分,它告诉人们从哪里下载DTD,以便系统能够理解配置的内容。

If we don’t include this definition in our configuration file won’t be a valid configuration file.

如果我们不把这个定义包括在我们的配置文件中,就不会是一个有效的配置文件。

5.2. Modules

5.2.模块

A config file is primarily composed of Modules. A module has an attribute name which represents what the module does. The value of the name attribute corresponds to a class in the plugin’s code which is executed when the plugin is run.

一个配置文件主要由模块组成。一个模块有一个属性name,代表该模块的作用。name属性的值对应于插件代码中的一个类,在插件运行时执行。

Let’s learn about the different modules present in the config above.

让我们了解一下上述配置中存在的不同模块。

5.3. Module Details

5.3.模块详细信息

  • Checker: Modules are structured in a tree that has the Checker module at the root. This module defines the properties that are inherited by all other modules of the configuration.
  • TreeWalker: This module checks the individual Java source files and defines properties that are applicable to checking such files.
  • AvoidStarImport: This module sets a standard for not using Star imports in our Java code. It also has a property that asks the plugin to report the severity of such issues as a warning. Thus, whenever such violations are found in the code, a warning will be flagged against them.

To read more about custom configurations follow this link.

要阅读有关自定义配置的更多信息,请遵循此链接

6. Report Analysis for the Spring-Rest Project

6.春晖计划的报告分析

In this section, we’re going to shed some light on an analysis done by Checkstyle, using the custom configuration created in section 5 above, on the spring-rest project available on GitHub as an example.

在本节中,我们将以GitHub上的spring-rest项目为例,阐明Checkstyle使用上文第5节中创建的自定义配置所做的分析。

6.1. Violation Report Generation

6.1.违规报告的生成

We’ve imported the configuration to Eclipse IDE and here is the violation report that is generated for the project:

我们已经将配置导入到Eclipse IDE中,下面是为该项目生成的违规报告。

Checkstyle violations chart

Checkstyle violations chart

The warnings reported here says that wildcard imports should be avoided in the code. We have two files that don’t comply with this standard. When we click on the warning it takes us to the Java file which has the violation.

这里报告的警告说,在代码中应该避免通配符导入。我们有两个文件不符合这个标准。当我们点击警告时,它会把我们带到有违规行为的Java文件中。

Here is how the HeavyResourceController.java file shows the warning reported:

下面是HeavyResourceController.java文件显示报告的警告。

warning

警告

6.2. Issue Resolution

6.2.问题解决

Using Star imports is not a good practice in general as it can create conflicts when two or more packages contain the same class.

一般来说,使用星形导入不是一个好的做法,因为当两个或多个包包含相同的类时,它可能会产生冲突。

As an example, consider the class List, which is available in packages java.util and java.awt both. If we use both the imports of java.util .* and java.awt.* our compiler will fail to compile the code, as List is available in both packages.

作为一个例子,考虑一下List,这个类java.utiljava.awt两个包中都有。如果我们同时使用 java.util .* 和 java.awt.* 的导入,我们的编译器将无法编译代码,因为 List 在两个包中都可用。

To resolve the issue mentioned above we organize the imports in both files and save them. Now when we run the plugin again we don’t see the violations and our code is now following the standards set in our custom configuration.

为了解决上述问题,我们在两个文件中都组织了导入,并保存了它们。现在,当我们再次运行该插件时,我们没有看到违规现象,我们的代码现在遵循了我们自定义配置中设置的标准。

7. Conclusion

7.结论

In this article, we’ve covered basics for integrating Checkstyle in our Java project.

在这篇文章中,我们已经介绍了将Checkstyle集成到我们的Java项目中的基本知识。

We’ve learned that it is a simple yet powerful tool that’s used to make sure that developers adhere to the coding standards set by the organization.

我们已经了解到,这是一个简单而强大的工具,用来确保开发人员遵守组织设定的编码标准。

The sample code we used for static analysis is available over on GitHub.

我们用于静态分析的示例代码可以在GitHub上找到