使用CheckStyle的必要性

一个软件开发团队往往需要有一个书面代码规范,用来统一我们的编程风格,但是这种靠主观约束的行为往往不是很靠谱,有些新来的员工他们的编程风格往往还会时不时得保持旧有的编程习惯,但是在提交代码的时候Code Reviewer看着一大坨的代码,以及快要到期的问题,只能感叹一下,口头“教育”一下新人,只要不是太难入眼一般就会让过,所以最终的代码经过长时间的维护就会成为一堆难以入眼的代码。所以最好的方式是在每个开发者自己的IDE中集成一个工具能够在修改完代码后对代码进行一次检查。CheckStyle就是为了解决这个需求产生的。

CheckStyle 顾名思义就是检查代码风格的,我们可以通过在一个团队中使用同一份代码风格约束文件来规范每个成员的代码规范。
CheckStyle 可以检查如下问题:

  • Javadoc注释
  • 命名约定
  • 标题
  • Import语句
  • 体积大小
  • 空白
  • 修饰符
  • 类设计等

Android Studio中配置CheckStyle

安装CheckStyle十分简单只要在AS插件库中查找CheckStyle-IDEA点击安装,然后重启AS即可。

在刚刚介绍的时候我们提到了代码风格约束文件,这个文件需要我们自己根据自己的需求定义,但是目前有很多现有的checkstyle 文件,网上较为多的是华为的checkstyle 文件,Googlecheckstyle 文件以及Sun 公司的checkstyle 文件。我们可以基于这些checkstyle 文件修改形成我们自己的checkstyle 文件。

在AS 中添加 checkstyle文件

当重启后,打开 AndroidStudio 的设置页面 settings -> Other Settings 你会发现多了一个 Checkstyle , 点击打开,如下图。

你会看到有一个 + 按钮,点击它即可添加自己的 checkstyle 文件。
可以点击面板的左上角下拉框 Rule 来在不同的checkstyle之间进行切换。

启动CheckStyle

选中一个文件右击在弹出的菜单项中,选择Check Current File来启动。面板上还提供了整个Module,整个Project进行check的按钮这个就不做过多的介绍了。

Google Java 代码规范

为了进一步规范Android开发者的编程规范 Google 提供了一份 Java 代码规范文档下面是它的地址:
http://google-styleguide.googlecode.com/svn/trunk/javaguide.html
下面是它对应的中文翻译:
http://hawstein.com/posts/google-java-style.html

其实上面介绍的都并不是重点,CheckStyle部分的重要部分是学会编程规范,以及如何根据编程规范配置checkstyle.xml文件,以及运行checkstyle之后出错的处理。但是需要强调下编程规范这东西不能按部就班,不要照本宣科,需要灵活对待。

checkStyle配置

checkstyle 提供了很多的配置项可供用户进行配置,下面是官网中提供的配置项:

http://checkstyle.sourceforge.net/checks.html

下面列出这些几百项的check项,需要注意的是每个check项下面还有很多的property。如果展开那就更恐怖了。

AbbreviationAsWordInName 	        The Check validate abbreviations(consecutive capital letters) length in identifier name, it also allow in enforce camel case naming.
AbstractClassName Ensures that the names of abstract classes conforming to some regular expression.
AnnotationLocation Check location of annotation on language elements.
AnnotationUseStyle This check controls the style with the usage of annotations.
AnonInnerLength Checks for long anonymous inner classes.
ArrayTrailingComma Checks if array initialization contains optional trailing comma.
ArrayTypeStyle Checks the style of array type definitions.
AtclauseOrder Checks the order of at-clauses.
AvoidEscapedUnicodeCharacters Restrict using Unicode escapes.
AvoidInlineConditionals Detects inline conditionals.
AvoidNestedBlocks Finds nested blocks.
AvoidStarImport Check that finds import statements that use the * notation.
AvoidStaticImport Check that finds static imports.
BooleanExpressionComplexity Restricts nested boolean operators (&&, ||, &, | and ^) to a specified depth (default = 3).
CatchParameterName Checks that catch parameter names conform to a format specified by the format property.
ClassDataAbstractionCoupling This metric measures the number of instantiations of other classes within the given class.
ClassFanOutComplexity The number of other classes a given class relies on.
ClassTypeParameterName Checks that class type parameter names conform to a format specified by the format property.
CommentsIndentation Controls the indentation between comments and surrounding code.
ConstantName Checks that constant names conform to a format specified by the format property.
CovariantEquals Checks that if a class defines a covariant method equals, then it defines method equals(java.lang.Object).
CustomImportOrder Checks that the groups of import declarations appear in the order specified by the user.
CyclomaticComplexity Checks cyclomatic complexity against a specified limit.
DeclarationOrder Checks that the parts of a class or interface declaration appear in the order suggested by the Code Conventions for the Java Programming Language.
DefaultComesLast Check that the default is after all the cases in a switch statement.
DescendantToken Checks for restricted tokens beneath other tokens.
DesignForExtension Checks that classes are designed for inheritance.
EmptyBlock Checks for empty blocks.
EmptyCatchBlock Checks for empty catch blocks with few options to skip violation.
EmptyForInitializerPad Checks the padding of an empty for initializer; that is whether a space is required at an empty for initializer, or such spaces are forbidden.
EmptyForIteratorPad Checks the padding of an empty for iterator; that is whether a space is required at an empty for iterator, or such spaces are forbidden.
EmptyLineSeparator Checks for blank line separators.
EmptyStatement Detects empty statements (standalone ';').
EqualsAvoidNull Checks that any combination of String literals is on the left side of an equals() comparison.
EqualsHashCode Checks that classes that override equals() also override hashCode().
ExecutableStatementCount Restricts the number of executable statements to a specified limit (default = 30).
ExplicitInitialization Checks if any class or object member explicitly initialized to default for its type value (null for object references, zero for numeric types and char and false for boolean.
FallThrough Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.
FileLength Checks for long source files.
FileTabCharacter Checks to see if a file contains a tab character.
FinalClass Checks that class which has only private constructors is declared as final.
FinalLocalVariable Ensures that local variables that never get their values changed, must be declared final.
FinalParameters Check that method/constructor/catch/foreach parameters are final.
GenericWhitespace Checks that the whitespace around the Generic tokens < and > are correct to the typical convention.
Header Checks the header of the source against a fixed header file.
HiddenField Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
HideUtilityClassConstructor Make sure that utility classes (classes that contain only static methods) do not have a public constructor.
IllegalCatch Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalImport Checks for imports from a set of illegal packages.
IllegalInstantiation Checks for illegal instantiations where a factory method is preferred.
IllegalThrows Throwing java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalToken Checks for illegal tokens.
IllegalTokenText Checks for illegal token text.
IllegalType Checks that particular class are never used as types in variable declarations, return values or parameters.
ImportControl Check that controls what packages can be imported in each package.
ImportOrder Ensures that groups of imports come in a specific order.
Indentation Checks correct indentation of Java Code.
InnerAssignment Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
InnerTypeLast Check nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations.
InterfaceIsType Implements Bloch, Effective Java, Item 17 - Use Interfaces only to define types.
InterfaceTypeParameterName Checks that interface type parameter names conform to a format specified by the format property.
JavadocMethod Checks the Javadoc of a method or constructor.
JavadocPackage Checks that all packages have a package documentation.
JavadocParagraph Checks Javadoc paragraphs.
JavadocStyle Custom Checkstyle Check to validate Javadoc.
JavadocTagContinuationIndentation Checks the indentation of the continuation lines in at-clauses.
JavadocType Checks the Javadoc of a type.
JavadocVariable Checks that a variable has Javadoc comment.
JavaNCSS This check calculates the Non Commenting Source Statements (NCSS) metric for Java source files and methods.
LeftCurly Checks the placement of left curly braces on types, methods and other blocks:
LineLength Checks for long lines.
LocalFinalVariableName Checks that local final variable names conform to a format specified by the format property.
LocalVariableName Checks that local, non-final variable names conform to a format specified by the format property.
MagicNumber Checks for magic numbers.
MemberName Checks that instance variable names conform to a format specified by the format property.
MethodCount Checks the number of methods declared in each type.
MethodLength Checks for long methods.
MethodName Checks that method names conform to a format specified by the format property.
MethodParamPad Checks the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list.
MethodTypeParameterName Checks that class type parameter names conform to a format specified by the format property.
MissingCtor Checks that classes (except abstract one) define a ctor and don't rely on the default one.
MissingDeprecated This class is used to verify that both the java.lang.Deprecated annotation is present and the @deprecated Javadoc tag is present when either is present.
MissingOverride This class is used to verify that the java.lang.Override annotation is present when the {@inheritDoc} javadoc tag is present.
MissingSwitchDefault Checks that switch statement has "default" clause.
ModifiedControlVariable Check for ensuring that for loop control variables are not modified inside the for block.
ModifierOrder Checks that the order of modifiers conforms to the suggestions in the Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3.
MultipleStringLiterals Checks for multiple occurrences of the same string literal within a single file.
MultipleVariableDeclarations Checks that each variable declaration is in its own statement and on its own line.
MutableException Ensures that exceptions (defined as any class name conforming to some regular expression) are immutable.
NeedBraces Checks for braces around code blocks.
NestedForDepth Restricts nested for blocks to a specified depth (default = 1).
NestedIfDepth Restricts nested if-else blocks to a specified depth (default = 1).
NestedTryDepth Restricts nested try-catch-finally blocks to a specified depth (default = 1).
NewlineAtEndOfFile Checks that there is a newline at the end of each file.
NoClone Checks that the clone method is not overridden from the Object class.
NoFinalizer Checks that no method having zero parameters is defined using the name finalize.
NoLineWrap Checks that chosen statements are not line-wrapped.
NonEmptyAtclauseDescription Checks that the at-clause tag is followed by description .
NoWhitespaceAfter Checks that there is no whitespace after a token.
NoWhitespaceBefore Checks that there is no whitespace before a token.
NPathComplexity Checks the npath complexity against a specified limit (default = 200).
OneStatementPerLine Checks that there is only one statement per line.
OneTopLevelClass Checks that each top-level class, interfaces or enum resides in a source file of its own.
OperatorWrap Checks line wrapping for operators.
OuterTypeFilename Checks that the outer type name and the file name match.
OuterTypeNumber Checks for the number of defined types at the "outer" level.
OverloadMethodsDeclarationOrder Checks that overload methods are grouped together.
PackageAnnotation This check makes sure that all package annotations are in the package-info.java file.
PackageDeclaration Ensures there is a package declaration and (optionally) in the correct directory.
PackageName Checks that package names conform to a format specified by the format property.
ParameterAssignment Disallow assignment of parameters.
ParameterName Checks that parameter names conform to a format specified by the format property.
ParameterNumber Checks the number of parameters that a method or constructor has.
ParenPad Checks the padding of parentheses; that is whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden, with the exception that it does not check for padding of the right parenthesis at an empty for iterator.
RedundantImport Checks for imports that are redundant.
RedundantModifier Checks for redundant modifiers in interface and annotation definitions, final modifier on methods of final classes, inner interface declarations that are declared as static, non public class constructors and enum constructors, nested enum definitions that are declared as static.
Regexp A check that makes sure that a specified pattern exists (or not) in the file.
RegexpHeader Checks the header of the source against a header file that contains a
RegexpMultiline Implementation of a check that looks that matches across multiple lines in any file type.
RegexpOnFilename Implementation of a check that matches based on file and/or folder path.
RegexpSingleline Implementation of a check that looks for a single line in any file type.
RegexpSinglelineJava Implementation of a check that looks for a single line in Java files.
RequireThis Checks that code doesn't rely on the "this" default.
ReturnCount Restricts return statements to a specified count (default = 2).
RightCurly Checks the placement of right curly braces.
SeparatorWrap Checks line wrapping with separators.
SimplifyBooleanExpression Checks for overly complicated boolean expressions.
SimplifyBooleanReturn Checks for overly complicated boolean return statements.
SingleLineJavadoc Checks that a JavaDoc block which can fit on a single line and doesn't contain at-clauses
SingleSpaceSeparator Checks that non-whitespace characters are separated by no more than one whitespace.
StaticVariableName Checks that static, non-final variable names conform to a format specified by the format property.
StringLiteralEquality Checks that string literals are not used with == or !=.
SummaryJavadoc Checks that Javadoc summary sentence does not contain phrases that are not recommended to use.
SuperClone Checks that an overriding clone() method invokes super.clone().
SuperFinalize Checks that an overriding finalize() method invokes super.finalize().
SuppressWarnings This check allows you to specify what warnings that
SuppressWarningsHolder This check allows for finding code that should not be reported by Checkstyle
ThrowsCount Restricts throws statements to a specified count (default = 4).
TodoComment A check for TODO comments.
TrailingComment The check to ensure that requires that comments be the only thing on a line.
Translation The TranslationCheck class helps to ensure the correct translation of code by checking property files for consistency regarding their keys.
TypecastParenPad Checks the padding of parentheses for typecasts.
TypeName Checks that type names conform to a format specified by the format property.
UncommentedMain Detects uncommented main methods.
UniqueProperties Detects duplicated keys in properties files.
UnnecessaryParentheses Checks if unnecessary parentheses are used in a statement or expression.
UnusedImports Checks for unused import statements.
UpperEll Checks that long constants are defined with an upper ell.
VariableDeclarationUsageDistance Checks the distance between declaration of variable and its first usage.
VisibilityModifier Checks visibility of class members.
WhitespaceAfter Checks that a token is followed by whitespace, with the exception that it does not check for whitespace after the semicolon of an empty for iterator.
WhitespaceAround Checks that a token is surrounded by whitespace.
WriteTag Outputs a JavaDoc tag as information.

一般我们不会自己从头到尾来编写checkstyle.xml,我们可以根据现有的配置表根据需求进行修改。因此我们要做的就是认识每个配置项,学会修改这些配置项。

一些公司的checkStyle配置文件

下面提供一些公司的checkStyle配置文件供大家参考:
Google CheckStyle 地址
Sun CheckStyle 地址

下面是网上流传较多的华为Checkstyle,我自己的checkstyle也是根据这个进行微调的,由于这个是有注释的所以转载过来给大家,也供自己以后备用:
转载自: http://blog.csdn.net/will_awoke/article/details/12705611

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<!-- Generated by RHY @will_awoke -->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<!-- Checks for Size Violations. -->
<!-- 检查文件的长度(行) default max=2000 -->
<module name="FileLength">
<property name="max" value="2500"/>
</module>

<!-- Checks that property files contain the same keys. -->
<!-- 检查**.properties配置文件 是否有相同的key
<module name="Translation">
</module>
-->
<module name="TreeWalker">
<!-- Checks for imports -->
<!-- 必须导入类的完整路径,即不能使用*导入所需的类 -->
<module name="AvoidStarImport"/>
<!-- 检查是否从非法的包中导入了类 illegalPkgs: 定义非法的包名称-->
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
<!-- 检查是否导入了不必显示导入的类-->
<module name="RedundantImport"/>
<!-- 检查是否导入的包没有使用-->
<module name="UnusedImports"/>

<!-- Checks for whitespace
<module name="EmptyForIteratorPad"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
-->

<!-- 检查类和接口的javadoc 默认不检查author 和version tags
authorFormat: 检查author标签的格式
versionFormat: 检查version标签的格式
scope: 可以检查的类的范围,例如:public只能检查public修饰的类,private可以检查所有的类
excludeScope: 不能检查的类的范围,例如:public,public的类将不被检查,但访问权限小于public的类仍然会检查,其他的权限以此类推
tokens: 该属性适用的类型,例如:CLASS_DEF,INTERFACE_DEF -->
<module name="JavadocType">
<property name="authorFormat" value="\S"/>
<property name="scope" value="protected"/>
<property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>
</module>

<!-- 检查方法的javadoc的注释
scope: 可以检查的方法的范围,例如:public只能检查public修饰的方法,private可以检查所有的方法
allowMissingParamTags: 是否忽略对参数注释的检查
allowMissingThrowsTags: 是否忽略对throws注释的检查
allowMissingReturnTag: 是否忽略对return注释的检查 -->
<module name="JavadocMethod">
<property name="scope" value="private"/>
<property name="allowMissingParamTags" value="false"/>
<property name="allowMissingThrowsTags" value="false"/>
<property name="allowMissingReturnTag" value="false"/>
<property name="tokens" value="METHOD_DEF"/>
<property name="allowUndeclaredRTE" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<!--允许get set 方法没有注释-->
<property name="allowMissingPropertyJavadoc" value="true"/>
</module>

<!-- 检查类变量的注释
scope: 检查变量的范围,例如:public只能检查public修饰的变量,private可以检查所有的变量 -->
<module name="JavadocVariable">
<property name="scope" value="private"/>
</module>

<!--option: 定义左大括号'{'显示位置,eol在同一行显示,nl在下一行显示
maxLineLength: 大括号'{'所在行行最多容纳的字符数
tokens: 该属性适用的类型,例:CLASS_DEF,INTERFACE_DEF,METHOD_DEF,CTOR_DEF -->
<module name="LeftCurly">
<property name="option" value="nl"/>
</module>

<!-- NeedBraces 检查是否应该使用括号的地方没有加括号
tokens: 定义检查的类型 -->
<module name="NeedBraces"/>

<!-- Checks the placement of right curly braces ('}') for else, try, and catch tokens. The policy to verify is specified using property option.
option: 右大括号是否单独一行显示
tokens: 定义检查的类型 -->
<module name="RightCurly">
<property name="option" value="alone"/>
</module>

<!-- 检查在重写了equals方法后是否重写了hashCode方法 -->
<module name="EqualsHashCode"/>

<!-- Checks for illegal instantiations where a factory method is preferred.
Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.
A simple example is the java.lang.Boolean class. In order to save memory and CPU cycles, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().
Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools. -->
<module name="IllegalInstantiation">
<property name="classes" value="java.lang.Boolean"/>
</module>

<!-- Checks for Naming Conventions. 命名规范 -->
<!-- local, final variables, including catch parameters -->
<module name="LocalFinalVariableName"/>

<!-- local, non-final variables, including catch parameters-->
<module name="LocalVariableName"/>

<!-- static, non-final fields -->
<module name="StaticVariableName">
<property name="format" value="(^[A-Z0-9_]{0,19}$)"/>
</module>

<!-- packages -->
<module name="PackageName" >
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
</module>

<!-- classes and interfaces -->
<module name="TypeName">
<property name="format" value="(^[A-Z][a-zA-Z0-9]{0,19}$)"/>
</module>

<!-- methods -->
<module name="MethodName">
<property name="format" value="(^[a-z][a-zA-Z0-9]{0,19}$)"/>
</module>

<!-- non-static fields -->
<module name="MemberName">
<property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,19}$)"/>
</module>

<!-- parameters -->
<module name="ParameterName">
<property name="format" value="(^[a-z][a-zA-Z0-9_]{0,19}$)"/>
</module>

<!-- constants (static, final fields) -->
<module name="ConstantName">
<property name="format" value="(^[A-Z0-9_]{0,19}$)"/>
</module>

<!-- 代码缩进 -->
<module name="Indentation">
</module>

<!-- Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
检查是否抛出了多余的异常
<module name="RedundantThrows">
<property name="logLoadErrors" value="true"/>
<property name="suppressLoadErrors" value="true"/>
</module>
-->

<!-- Checks for overly complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc.
检查boolean值是否冗余的地方
Rationale: Complex boolean logic makes code hard to understand and maintain. -->
<module name="SimplifyBooleanExpression"/>

<!-- Checks for overly complicated boolean return statements. For example the following code
检查是否存在过度复杂的boolean返回值
if (valid())
return false;
else
return true;
could be written as
return !valid();
The Idea for this Check has been shamelessly stolen from the equivalent PMD rule. -->
<module name="SimplifyBooleanReturn"/>

<!-- Checks that a class which has only private constructors is declared as final.只有私有构造器的类必须声明为final-->
<module name="FinalClass"/>

<!-- Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.
确保Utils类(只提供static方法和属性的类)没有public构造器。
Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.
If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:
public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
public static int count(char c, String s) {
// ...
}
}
<module name="HideUtilityClassConstructor"/>
-->

<!-- Checks visibility of class members. Only static final members may be public; other class members must be private unless property protectedAllowed or packageAllowed is set.
检查class成员属性可见性。只有static final 修饰的成员是可以public的。其他的成员属性必需是private的,除非属性protectedAllowed或者packageAllowed设置了true.
Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default). Note: Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow CMP for EJB 1.1 with the default settings. With EJB 2.0 it is not longer necessary to have public access for persistent fields, hence the default has been changed.
Rationale: Enforce encapsulation. 强制封装 -->
<module name="VisibilityModifier"/>

<!-- 每一行只能定义一个变量 -->
<module name="MultipleVariableDeclarations">
</module>

<!-- Checks the style of array type definitions. Some like Java-style: public static void main(String[] args) and some like C-style: public static void main(String args[])
检查再定义数组时,采用java风格还是c风格,例如:int[] num是java风格,int num[]是c风格。默认是java风格-->
<module name="ArrayTypeStyle">
</module>

<!-- Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.
<module name="MagicNumber">
</module>
-->

<!-- A check for TODO: comments. Actually it is a generic regular expression matcher on Java comments. To check for other patterns in Java comments, set property format.
检查是否存在TODO(待处理) TODO是javaIDE自动生成的。一般代码写完后要去掉。
-->
<module name="TodoComment"/>

<!-- Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification, Section 3.10.1.
检查是否在long类型是否定义了大写的L.字母小写l和数字1(一)很相似。
looks a lot like 1. -->
<module name="UpperEll"/>

<!-- Checks that switch statement has "default" clause. 检查switch语句是否有‘default’从句
Rationale: It's usually a good idea to introduce a default case in every switch statement.
Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch,
e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type. -->
<module name="MissingSwitchDefault"/>

<!--检查switch中case后是否加入了跳出语句,例如:return、break、throw、continue -->
<module name="FallThrough"/>

<!-- Checks the number of parameters of a method or constructor. max default 7个. -->
<module name="ParameterNumber">
<property name="max" value="5"/>
</module>

<!-- 每行字符数 -->
<module name="LineLength">
<property name="max" value="200"/>
</module>

<!-- Checks for long methods and constructors. max default 150行. max=300 设置长度300 -->
<module name="MethodLength">
<property name="max" value="300"/>
</module>

<!-- ModifierOrder 检查修饰符的顺序,默认是 public,protected,private,abstract,static,final,transient,volatile,synchronized,native -->
<module name="ModifierOrder">
</module>

<!-- 检查是否有多余的修饰符,例如:接口中的方法不必使用public、abstract修饰 -->
<module name="RedundantModifier">
</module>

<!--- 字符串比较必须使用 equals() -->
<module name="StringLiteralEquality">
</module>

<!-- if-else嵌套语句个数 最多4层 -->
<module name="NestedIfDepth">
<property name="max" value="3"/>
</module>

<!-- try-catch 嵌套语句个数 最多2层 -->
<module name="NestedTryDepth">
<property name="max" value="2"/>
</module>

<!-- 返回个数 -->
<module name="ReturnCount">
<property name="max" value="5"/>
<property name="format" value="^$"/>
</module>
</module>
</module>

CheckStyle 运行结果分析

CheckStyle 与FindBug以及Lint相比之下做的比较不足的是在IDE插件中没有提供每个运行结果警告的说明,在遇到问题的时候只能到上面提到的网站上查找原因,并且上述的网站访问速度很慢,但是好在一般点击到报错或者警告的地方一般都会大概知道是真么原因导致,反倒是不是很难。
但是今天突然上网的时候看到一篇别人写的博客,上面记录了较为常见的运行结果的说明,为了避免原博客这部分内容丢失所以特地将这篇博客转载过来:

大家也可以通过这个链接访问原始博客:http://blog.csdn.net/zhengqiqiqinqin/article/details/8450416

1.Missing a Javadoc comment:缺少JavaDoc注释
2.First sentence should end with a period:你的注释的第一行文字结束应该加上一个"."
3.Expected @throws tag for 'Exception':在注释中希望有@throws的说明,在方法前得注释中添加这样一行:* @throws Exception if has error(异常说明)
4.Parameter docType should be final:参数docType应该为final类型 解决方法:在参数docType前面加个final
5.Variable “ABC” must match pattern “^[a-z][a-zA-Z0-9]*$”变量“ABC”不符合命名规则“^[a-z][a-zA-Z0-9]*$”解决方法:把这个命名改成符合规则的命名 “aBC”
6.Utility classes should not have a public or default constructor. 接口中的内部类中不应该有公共的或者默认的构造方法
解决方法:在内部类中,定义一个私有的构造方法,然后内部类声明为final类型。如果前面有static,那么final还必须放在static之后
7.'{' is not preceded with whitespace.大括号后面必须空一格
8.'public' modifier out of order with the JLS suggestions. public顺序错误=
9.Method 'deleteChild' is not designed for extension - needs to be abstract, final or empty. 不是拓展或继承的方法,必须指定abstract,final或空
1Type is missing a javadoc commentClass 缺少类型说明
2“{” should be on the previous line“{” 应该位于前一行。解决方法:把“{”放到上一行去
3Methos is missing a javadoc comment 方法前面缺少javadoc注释。解决方法:添加javadoc注释 类似这样:
/**
* set default mock parameter.(方法说明)
* @param additionalParameters parameter additional(参数名称)
* @return data manager(返回值说明)
* @throws Exception if has error(异常说明)
*/
4 Expected @throws tag for “Exception”在注释中希望有@throws的说明
解决方法:在方法前得注释中添加这样一行:* @throws Exception if has error(异常说明)
5“.” Is preceeded with whitespace “.” 前面不能有空格。解决方法:把“(”前面的空格去掉
6“.” Is followed by whitespace“.” 后面不能有空格。解决方法:把“)”后面的空格去掉
7“=” is not preceeded with whitespace“=” 前面缺少空格。解决方法:在“=”前面加个空格
8“=” is not followed with whitespace“=” 后面缺少空格。解决方法:在“=”后面加个空格
9“}” should be on the same line“}” 应该与下条语句位于同一行。解决方法:把“}”放到下一行的前面
10Unused @param tag for “unused”没有参数“unused”,不需注释
解决方法:“* @param unused parameter additional(参数名称)” 把这行unused参数的注释去掉“
11Variable “CA” missing javadoc变量“CA”缺少javadoc注释
解决方法:在“CA“变量前添加javadoc注释:/** CA. */(注意:一定记得加上“.”)
12Line longer than 80characters行长度超过80 。解决方法:把它分成多行写。必要时候,可以ctrl+shift+f
13Line contains a tab character行含有”tab” 字符。快速解决方法:可以使用editplus中的format功能,把tab字符转化为空格,然后保存Editplus英文版安装文件在我机子上有。需要的可以来拷贝。注册Editplus,点击安装文件中注册的文件
14Redundant “Public” modifier冗余的“public” modifier 。解决方法:冗余的“public
15Final modifier out of order with the JSL suggestion Final modifier的顺序错误
16Avoid using the “.*” form of importImport格式避免使用“.*”
17Redundant import from the same package从同一个包中Import内容
18Unused import-java.util.listImport进来的java.util.list没有被使用。解决方法:去掉导入的多余的类
19Duplicate import to line 13重复Import同一个内容 解决方法:去掉导入的多余的类
20Import from illegal package从非法包中 Import内容
21while” construct must use “{}” “while” 语句缺少“{}”
22Variable “sTest1” must be private and have accessor method变量“sTest1”应该是private的,并且有调用它的方法
23Variable “ABC” must match pattern “^[a-z][a-zA-Z0-9]*$”变量“ABC”不符合命名规则“^[a-z][a-zA-Z0-9]*$”解决方法:把这个命名改成符合规则的命名 “aBC”
24“(” is followed by whitespace“(” 后面不能有空格 25“)”is proceeded by whitespace“)” 前面不能有空格
解决方法:把前面或者后面的空格去掉
25、First sentence should end with a period.解决方法:你的注释的第一行文字结束应该加上一个"."
26、Redundant throws: 'NameNotFoundException' is subclass of 'NamingException'. 'NameNotFoundException ''NamingException'的子类重复抛出异常。
解决方法:如果抛出两个异常,一个异常类是另一个的子类,那么只需要写父类
去掉NameNotFoundException异常,对应的javadoc注释异常注释说明也需要去掉
27、Parameter docType should be final. 参数docType应该为final类型 解决方法:在参数docType前面加个final
28、Line has trailing spaces. 多余的空行 解决方法:去掉这行空行
29.Must have at least one statement. 至少一个声明
解决方法:} catch (NumberFormatException nfe) {
LOG.error("Auto Renews the agreement failed", nfe);//异常捕捉里面不能为空,在异常里面加一句话。如打印等等
30'>' is not followed by whitespace.并且又有 '(' is preceded with whitespace.
定义集合和枚举的时候的时候,最后一个“>”后面要有空格,“(”前面不容许有空格。解决方法:去掉泛型
31、Got an exception - java.lang.RuntimeException: Unable to get class information for @throws tag 'SystemException'.原因:不合理的throws
解决方法:要确保某些类型,如某些类、接口不被throws。把声明的异常去掉。在实现类中抛出异常
网上参考解决方法:1、这是CheckStyle报的错。通常需要Refreh, clean/build这个Project. 如果不行,可以尝试clean all projects, restart Eclipse.
2、因为编译好的类没有在checkstyle的classpath中.所以, 只要将编译好的class配置到在<checkstyle/>的classpath中就没有这个问题了.另外, 还发现checkstyle的line length好像也有点问题, 明明没有超过120个字符, 却还是报错.无奈, 我把Eclipse中java > code style > formatter中的Maximum line with改成了100, 然后format一下, 基本就没有问题了
32、File does not end with a newline.解决方法:删掉报错的类,新建一个同名的类,把代码全部复制过去
33、Utility classes should not have a public or default constructor. 接口中的内部类中不应该有公共的或者默认的构造方法
解决方法:在内部类中,定义一个私有的构造方法,然后内部类声明为final类型。如果前面有static,那么final还必须放在static之后
34、Variable 'functionCode' must be private and have accessor methods.变量要改成private然后提供访问的方法
解决方法:给这些变量的修饰符改成private,然后提供set,get方法,并加上对应的方法javadoc注释、参数注释。并在返回值和参数类型前添加final。并把调用了这个变量的地方改成通过方法访问
35. 'X' hides a field.
public class Foo
{
private int bar;

public Foo(int bar)
{
this.bar = bar;
}
public final int getBar()
{
return bar;
}
}
全局private int bar;和局部public Foo(int bar)的bar变量名字重复。
解决方法:把方法里面的参数名称改变下就可以了public Foo(int newBar)
{
this.bar = newBar;
}。
36、Got an exception - Unexpected character 0xfffd in identifier
这是因为CheckStyle不能识别制定的编码格式。
网上参考解决方法:
1、Eclipse中可以配置,在Other-->checker中可以指定
2、可以修改checkstyle配置文件:
<module name="Checker">
<property name="severity" value="warning"/>
<property name="charset" value="UTF-8"/>
<module name="TreeWalker">
如果是UTF-8的话,就添加加粗的那条语句,就可以了。
37、 Got an exception - java.lang.RuntimeException: Unable to get class information for @throws tag *whatever*.
网上参考解决方法:选中CheckSytle的JavaDoc --> Method JavaDoc --> logLoadErrors。如果是CheckStyle自己加载时出错的,打个Log就可以了,不要整出Errors吓人。
还有一处也可能包出同样的错误。Coding Problems --> Redundant Throws --> logLoadErrors选中即可
38、Expected @param tag for 'dataManager'. 缺少dataManager参数的注释 解决方法:在注释中添加@param dataManager DataManager
网上一些其他错误的解答:
1. Parameter X should be final.
public class Foo
{
private int bar;

public Foo(int bar)
{
this.bar = bar;
}
public final int getBar()
{
return bar;
}
}
解释:public Foo(int bar)的局部变量,被认为是不可改变的,检查需要加上final关键字定义public Foo(final int bar)此错误,可以忽略不检查。

2. Redundant 'X' modifier.
public interface CacheHRTreeService extends Manager {
/**
* Organization Tree
* @param orgDto
* @return
* @throws Exception
*/
public void setOrganization(OrganizationDTO orgDto) throws Exception;
/**
* Organization Tree
* @return
* @throws Exception
*/
public OrganizationDTO getOrganization() throws Exception;
......
}
解释:多余的字段。public OrganizationDTO getOrganization() throws Exception;此时public为多余的字段,因为interface定义的时候,就是public的。需要检查。
3. - Class X should be declared as final.
解释:对于单例设计模式,要求返回唯一的类对象。但是HRFactory和ContextFactory为优化的两个类,不需求检查。
其他的单例类,依然需要进行检查。
4. - Method 'addChildrenId' is not designed for extension - needs to be
abstract, final or empty.
解释:通过父类继承的,此类有点特殊可以忽略此类。
5. Variable 'id' must be private and have accessor methods.解释:BaseHRDTO类,为父类,属性给子类继承,比较特殊。但是其他的类,声名需要加上范围'private'关键字。需要检查。
6. -Array brackets at illegal position.解释:代码写法,习惯不一样。需要检查,仅仅提示

其他较好的博客推荐:
www.blogjava.net/japper/archive/2012/05/24/379054.html

Contents
  1. 1. 使用CheckStyle的必要性
  2. 2. Android Studio中配置CheckStyle
  3. 3. 在AS 中添加 checkstyle文件
  4. 4. 启动CheckStyle
  5. 5. Google Java 代码规范
  6. 6. checkStyle配置
  7. 7. 一些公司的checkStyle配置文件
  8. 8. CheckStyle 运行结果分析