JAVA 静态代码分析--规范检查-checkstyle

简介

插件的用途就不多说了,主要用于JAVA代码规范检测,默认用的sun的一套检查标准,也可以自己定义。这里讲的版本是5.6

在eclipse中安装checkstyle

help--> eclipse marketplace 搜索 checkstyle,安装即可。

用checkstyle检测

选择要检测的项目,右键点击checkstyle--->check code with checkstyle即可

会生成两项报告,点击windows-->show view ,找到checkstyle即可


生成的结果如下:


还有一个饼状图


修改checkstyle参数

点击eclpse-->windows-->preferences


可以看到,目前使用的是sun checks,点击configure,会发现,The configuration can not be edited.

也就是自带的两个内置规则是不能编辑的,于是我们copy出一份自己的规则,点击copy,起个名字,确认即可。


再次打开,就可编辑了。

例如我们之前检测结果中,问题最大的一项是line is longer than X characters,这里默认值是80个字符,有点太短了,我

把它改成100,找到Size Violations,离得 max line length,打开,默认是80,改成100即可。


去掉对某个文件的统计

实际操作中,由于项目中包含一个.ttc的字库,导致统计结果中几乎被这个文件占掉了一半,可以右键点击这个文件,-->checkstyle-->clear checkstyle violation,
统计列表随机跟着改变。

各种检查提示的解释


utility classes should not have a public or default constructor

还会有提示:All methods are static. Consider using Singleton instead.Alternatively,you could add a private constructor or make the class abstract to silence this warning.
工具类不应该有默认或者公共的构造函数,也就是说这个类里可能方法都是static,那就不需要构造它的实例,因此应该给加一个private的构造函数,就不会报这个错了。

a class which only has private constructors should be final

例如上一个,加了private构造函数,又会出这个,把class设置成final即可。

Array brackets at illegal positon

String array[] = {}; 改成

String[] array = {};即可,应该是指位置不标准。

conditional logic can be removed

例如:

if ("post".equalsIgnoreCase(method)) {
return true;
} else {
return false;
}

会报错,conditional logic can be removed,条件逻辑可以删掉,改成如下方式:

return "post".equalsIgnoreCase(method);

即可,比较简洁

X is not followed by whitespace

符号的左右要有空格

X modifier out of order with the JLS suggestions

是修饰符顺序不符合标准。例如:
public final static String SAFE_EVENT_AUDIT_RECORD = "安全事件类";
改成:
public static final String SAFE_EVENT_AUDIT_RECORD = "安全事件类";
即可

Name ''X'' must match pattern ''X''.

要求变量必须符合正则表达式定义的规则,
例如变量: must match pattern '^[a-z][a-zA-Z0-9]*$'
变量必须小写字母开头,可以包含大写字母和数字,但是不能包含下划线
这里如果需要改名,可以使用ECLIPSE的重新命名功能进行批量修改,快捷键是ALT + SHIFT + R
常量:^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
常量大写字母开头,包含_和数字。

参数含义


来自:http://checkstyle.sourceforge.net/availablechecks.html

AbstractClassNameEnsures that the names of abstract classes conforming to some regular expression.
AnnotationUseStyleThis check controls the style with the usage of annotations.
AnonInnerLengthChecks for long anonymous inner classes.
ArrayTrailingCommaChecks if array initialization contains optional trailing comma.
ArrayTypeStyleChecks the style of array type definitions.
AvoidInlineConditionalsDetects inline conditionals.
AvoidNestedBlocksFinds nested blocks.
AvoidStarImportCheck that finds import statements that use the * notation.
AvoidStaticImportCheck that finds static imports.
BooleanExpressionComplexityRestricts nested boolean operators (&&, ||, &, | and ^) to a specified depth (default = 3).
ClassDataAbstractionCouplingThis metric measures the number of instantiations of other classes within the given class.
ClassFanOutComplexityThe number of other classes a given class relies on.
ClassTypeParameterNameChecks that class type parameter names conform to a format specified by the format property.
ConstantNameChecks that constant names conform to a format specified by the format property.
CovariantEqualsChecks that if a class defines a covariant method equals, then it defines method equals(java.lang.Object).
CyclomaticComplexityChecks cyclomatic complexity against a specified limit.
DeclarationOrderChecks that the parts of a class or interface declaration appear in the order suggested by the Code Conventions for the Java Programming Language.
DefaultComesLastCheck that the default is after all the cases in a switch statement.
DescendantTokenChecks for restricted tokens beneath other tokens.
DesignForExtensionChecks that classes are designed for inheritance.
EmptyBlockChecks for empty blocks.
EmptyForInitializerPadChecks the padding of an empty for initializer; that is whether a space is required at an empty for initializer, or such spaces are forbidden.
EmptyForIteratorPadChecks the padding of an empty for iterator; that is whether a space is required at an empty for iterator, or such spaces are forbidden.
EmptyStatementDetects empty statements (standalone ';').
EqualsAvoidNullChecks that any combination of String literals with optional assignment is on the left side of an equals() comparison.
EqualsHashCodeChecks that classes that override equals() also override hashCode().
ExecutableStatementCountRestricts the number of executable statements to a specified limit (default = 30).
ExplicitInitializationChecks 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.
FallThroughChecks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.
FileLengthChecks for long source files.
FileTabCharacterChecks to see if a file contains a tab character.
FinalClassChecks that class which has only private ctors is declared as final.
FinalLocalVariableEnsures that local variables that never get their values changed, must be declared final.
FinalParametersCheck that method/constructor/catch/foreach parameters are final.
GenericWhitespaceChecks that the whitespace around the Generic tokens < and > are correct to the typical convention.
HeaderChecks the header of the source against a fixed header file.
HiddenFieldChecks that a local variable or a parameter does not shadow a field that is defined in the same class.
HideUtilityClassConstructorMake sure that utility classes (classes that contain only static methods) do not have a public constructor.
IllegalCatchCatching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalImportChecks for imports from a set of illegal packages.
IllegalInstantiationChecks for illegal instantiations where a factory method is preferred.
IllegalThrowsThrowing java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalTokenChecks for illegal tokens.
IllegalTokenTextChecks for illegal token text.
IllegalTypeChecks that particular class are never used as types in variable declarations, return values or parameters.
ImportControlCheck that controls what packages can be imported in each package.
ImportOrderEnsures that groups of imports come in a specific order.
IndentationChecks correct indentation of Java Code.
InnerAssignmentChecks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
InnerTypeLastCheck nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations.
InterfaceIsTypeImplements Bloch, Effective Java, Item 17 - Use Interfaces only to define types.
JUnitTestCaseEnsures that the setUp(), tearDown()methods are named correctly, have no arguments, return void and are either public or protected.
JavaNCSSThis check calculates the Non Commenting Source Statements (NCSS) metric for java source files and methods.
JavadocMethodChecks the Javadoc of a method or constructor.
JavadocPackageChecks that all packages have a package documentation.
JavadocStyleCustom Checkstyle Check to validate Javadoc.
JavadocTypeChecks the Javadoc of a type.
JavadocVariableChecks that a variable has Javadoc comment.
LeftCurlyChecks the placement of left curly braces on types, methods and other blocks:
LineLengthChecks for long lines.
LocalFinalVariableNameChecks that local final variable names conform to a format specified by the format property.
LocalVariableNameChecks that local, non-final variable names conform to a format specified by the format property.
MagicNumberChecks for magic numbers.
MemberNameChecks that instance variable names conform to a format specified by the format property.
MethodCountChecks the number of methods declared in each type.
MethodLengthChecks for long methods.
MethodNameChecks that method names conform to a format specified by the format property.
MethodParamPadChecks the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list.
MethodTypeParameterNameChecks that class type parameter names conform to a format specified by the format property.
MissingCtorChecks that classes (except abstract one) define a ctor and don't rely on the default one.
MissingDeprecatedThis class is used to verify that both the
MissingOverrideThis class is used to verify that the
MissingSwitchDefaultChecks that switch statement has "default" clause.
ModifiedControlVariableCheck for ensuring that for loop control variables are not modified inside the for block.
ModifierOrderChecks 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.
MultipleStringLiteralsChecks for multiple occurrences of the same string literal within a single file.
MultipleVariableDeclarationsChecks that each variable declaration is in its own statement and on its own line.
MutableExceptionEnsures that exceptions (defined as any class name conforming to some regular expression) are immutable.
NPathComplexityChecks the npath complexity against a specified limit (default = 200).
NeedBracesChecks for braces around code blocks.
NestedForDepthRestricts nested for blocks to a specified depth (default = 1).
NestedIfDepthRestricts nested if-else blocks to a specified depth (default = 1).
NestedTryDepthRestricts nested try-catch-finally blocks to a specified depth (default = 1).
NewlineAtEndOfFileChecks that there is a newline at the end of each file.
NoCloneChecks that the clone method is not overridden from the Object class.
NoFinalizerChecks that no method having zero parameters is defined using the name finalize.
NoWhitespaceAfterChecks that there is no whitespace after a token.
NoWhitespaceBeforeChecks that there is no whitespace before a token.
OneStatementPerLineChecks there is only one statement per line.
OperatorWrapChecks line wrapping for operators.
OuterTypeFilenameChecks that the outer type name and the file name match.
OuterTypeNumberChecks for the number of defined types at the "outer" level.
PackageAnnotationThis check makes sure that all package annotations are in the package-info.java file.
PackageDeclarationEnsures there is a package declaration and (optionally) in the correct directory.
PackageNameChecks that package names conform to a format specified by the format property.
ParameterAssignmentDisallow assignment of parameters.
ParameterNameChecks that parameter names conform to a format specified by the format property.
ParameterNumberChecks the number of parameters that a method or constructor has.
ParenPadChecks 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.
RedundantImportChecks for imports that are redundant.
RedundantModifierChecks for redundant modifiers in interface and annotation definitions.
RedundantThrowsChecks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
RegexpA check that makes sure that a specified pattern exists (or not) in the file.
RegexpHeaderChecks the header of the source against a header file that contains a
RegexpMultilineImplementation of a check that looks that matches across multiple lines in any file type.
RegexpSinglelineImplementation of a check that looks for a single line in any file type.
RegexpSinglelineJavaImplementation of a check that looks for a single line in Java files.
RequireThisChecks that code doesn't rely on the "this" default.
ReturnCountRestricts return statements to a specified count (default = 2).
RightCurlyChecks the placement of right curly braces.
SimplifyBooleanExpressionChecks for overly complicated boolean expressions.
SimplifyBooleanReturnChecks for overly complicated boolean return statements.
StaticVariableNameChecks that static, non-final variable names conform to a format specified by the format property.
StrictDuplicateCodePerforms a line-by-line comparison of all code lines and reports duplicate code if a sequence of lines differs only in indentation.
StringLiteralEqualityChecks that string literals are not used with == or !=.
SuperCloneChecks that an overriding clone() method invokes super.clone().
SuperFinalizeChecks that an overriding finalize() method invokes super.finalize().
SuppressWarningsThis check allows you to specify what warnings that
SuppressWarningsHolderThis check allows for finding code that should not be reported by Checkstyle
ThrowsCountRestricts throws statements to a specified count (default = 1).
TodoCommentA check for TODO comments.
TrailingCommentThe check to ensure that requires that comments be the only thing on a line.
TranslationThe TranslationCheck class helps to ensure the correct translation of code by checking property files for consistency regarding their keys.
TypeNameChecks that type names conform to a format specified by the format property.
TypecastParenPadChecks the padding of parentheses for typecasts.
UncommentedMainDetects uncommented main methods.
UnnecessaryParenthesesChecks if unnecessary parentheses are used in a statement or expression.
UnusedImportsChecks for unused import statements.
UpperEllChecks that long constants are defined with an upper ell.
VisibilityModifierChecks visibility of class members.
WhitespaceAfterChecks 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.
WhitespaceAroundChecks that a token is surrounded by whitespace.
WriteTagOutputs a JavaDoc tag as information.


参考:

JAVA 代码分析 http://www.oschina.net/question/129540_23043

http://darkranger.iteye.com/blog/657737

官网 http://checkstyle.sourceforge.net/

http://www.51testing.com/html/34/106134-92594.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

day walker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值