1. 程式人生 > >JAVA 靜態程式碼分析--規範檢查-checkstyle

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]+)*$ 常量大寫字母開頭,包含_和數字。

引數含義

Ensures that the names of abstract classes conforming to some regular expression.
This check controls the style with the usage of annotations.
Checks for long anonymous inner classes.
Checks if array initialization contains optional trailing comma.
Checks the style of array type definitions.
Check that finds import statements that use the * notation.
Check that finds static imports.
Restricts nested boolean operators (&&, ||, &, | and ^) to a specified depth (default = 3).
This metric measures the number of instantiations of other classes within the given class.
The number of other classes a given class relies on.
Checks that class type parameter names conform to a format specified by the format property.
Checks that constant names conform to a format specified by the format property.
Checks that if a class defines a covariant method equals, then it defines method equals(java.lang.Object).
Checks cyclomatic complexity against a specified limit.
Check that the default is after all the cases in a switch statement.
Checks for restricted tokens beneath other tokens.
Checks that classes are designed for inheritance.
Checks for empty blocks.
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.
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.
Detects empty statements (standalone ';').
Checks that any combination of String literals with optional assignment is on the left side of an equals() comparison.
Checks that classes that override equals() also override hashCode().
Restricts the number of executable statements to a specified limit (default = 30).
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.
Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.
Checks for long source files.
Checks to see if a file contains a tab character.
Checks that class which has only private ctors is declared as final.
Ensures that local variables that never get their values changed, must be declared final.
Check that method/constructor/catch/foreach parameters are final.
Checks that the whitespace around the Generic tokens < and > are correct to the typical convention.
Checks the header of the source against a fixed header file.
Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
Make sure that utility classes (classes that contain only static methods) do not have a public constructor.
Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.
Checks for imports from a set of illegal packages.
Checks for illegal instantiations where a factory method is preferred.
Throwing java.lang.Error or java.lang.RuntimeException is almost never acceptable.
Checks for illegal tokens.
Checks for illegal token text.
Checks that particular class are never used as types in variable declarations, return values or parameters.
Check that controls what packages can be imported in each package.
Ensures that groups of imports come in a specific order.
Checks correct indentation of Java Code.
Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
Check nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations.
Implements Bloch, Effective Java, Item 17 - Use Interfaces only to define types.
Ensures that the setUp(), tearDown()methods are named correctly, have no arguments, return void and are either public or protected.
This check calculates the Non Commenting Source Statements (NCSS) metric for java source files and methods.
Checks the Javadoc of a method or constructor.
Checks that all packages have a package documentation.
Custom Checkstyle Check to validate Javadoc.
Checks the Javadoc of a type.
Checks that a variable has Javadoc comment.
Checks the placement of left curly braces on types, methods and other blocks:
Checks for long lines.
Checks that local final variable names conform to a format specified by the format property.
Checks that local, non-final variable names conform to a format specified by the format property.
Checks for magic numbers.
Checks that instance variable names conform to a format specified by the format property.
Checks the number of methods declared in each type.
Checks for long methods.
Checks that method names conform to a format specified by the format property.
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.
Checks that class type parameter names conform to a format specified by the format property.
Checks that classes (except abstract one) define a ctor and don't rely on the default one.
This class is used to verify that both the
This class is used to verify that the
Checks that switch statement has "default" clause.
Check for ensuring that for loop control variables are not modified inside the for block.
Checks for multiple occurrences of the same string literal within a single file.
Checks that each variable declaration is in its own statement and on its own line.
Ensures that exceptions (defined as any class name conforming to some regular expression) are immutable.
Checks the npath complexity against a specified limit (default = 200).
Checks for braces around code blocks.
Restricts nested for blocks to a specified depth (default = 1).
Restricts nested if-else blocks to a specified depth (default = 1).
Restricts nested try-catch-finally blocks to a specified depth (default = 1).
Checks that there is a newline at the end of each file.
Checks that the clone method is not overridden from the Object class.
Checks that no method having zero parameters is defined using the name finalize.
Checks that there is no whitespace after a token.
Checks that there is no whitespace before a token.
Checks there is only one statement per line.
Checks line wrapping for operators.
Checks that the outer type name and the file name match.
Checks for the number of defined types at the "outer" level.
This check makes sure that all package annotations are in the package-info.java file.
Ensures there is a package declaration and (optionally) in the correct directory.
Checks that package names conform to a format specified by the format property.
Disallow assignment of parameters.
Checks that parameter names conform to a format specified by the format property.
Checks the number of parameters that a method or constructor has.
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.
Checks for imports that are redundant.
Checks for redundant modifiers in interface and annotation definitions.
Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
A check that makes sure that a specified pattern exists (or not) in the file.
Checks the header of the source against a header file that contains a
Implementation of a check that looks that matches across multiple lines in any file type.
Implementation of a check that looks for a single line in any file type.
Implementation of a check that looks for a single line in Java files.
Checks that code doesn't rely on the "this" default.
Restricts return statements to a specified count (default = 2).
Checks the placement of right curly braces.
Checks for overly complicated boolean expressions.
Checks for overly complicated boolean return statements.
Checks that static, non-final variable names conform to a format specified by the format property.
Performs a line-by-line comparison of all code lines and reports duplicate code if a sequence of lines differs only in indentation.
Checks that string literals are not used with == or !=.
Checks that an overriding clone() method invokes super.clone().
Checks that an overriding finalize() method invokes super.finalize().
This check allows you to specify what warnings that
This check allows for finding code that should not be reported by Checkstyle
Restricts throws statements to a specified count (default = 1).
A check for TODO comments.
The check to ensure that requires that comments be the only thing on a line.
The TranslationCheck class helps to ensure the correct translation of code by checking property files for consistency regarding their keys.
Checks that type names conform to a format specified by the format property.
Checks the padding of parentheses for typecasts.
Detects uncommented main methods.
Checks if unnecessary parentheses are used in a statement or expression.
Checks for unused import statements.
Checks that long constants are defined with an upper ell.
Checks visibility of class members.
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.
Checks that a token is surrounded by whitespace.
Outputs a JavaDoc tag as information.

參考:

JAVA 程式碼分析 http://www.oschina.net/question/129540_23043