CheckStyle的安裝及使用

CheckStyle是SourceForge下的一個項目,提供了一個幫助JAVA開發人員遵照某些編碼規範的工具。它可以自動化代碼規範檢查過程,從而使得開發人員從這項重要,可是枯燥的任務中解脫出來。java

下載地址:http://sourceforge.net/projects/eclipse-cs/express

如下是詳細的安裝步驟數組

1在官網下載最新版本網絡

打開以上的下載地址,進入下載頁面,點擊「download」開始插件的下載less

wps2B13.tmp

如下爲解壓文件目錄:(主要文件爲:features、plugins)eclipse

wps2B23.tmp

2採用link方式安裝eclipse插件curl

選擇eclipse圖標,右鍵選擇「打開文件位置」,打開eclipse的安裝目錄。ide

wps2B34.tmp

在該目錄下新建文件夾「myplu」,將剛纔壓縮包中的features、plugins拷貝到myplu目錄。工具

打開eclipse主目錄下的dropins文件夾,新建checkstyle.link文件。(擴展名爲.link),使用記事本打開該文件,填寫剛纔的myplu路徑,如:path=D://soft//Install//eclipse//myplu測試

wps2B35.tmp

3驗證安裝是否成功

從新啓動eclipse,選擇「window」--「preferences」,查看是否存在Checkstyle選擇,若存在說明安裝成功。如圖

wps2B45.tmp

4配置Checksytel

選擇「window」--「preferences」--「Checkstyle」,點擊左側的New按鈕,出現添加新配置選項。

wps2B56.tmp

在Type中選擇:External configuration file

Name:本身根據本身實際需求自定義名稱

Location:選擇Checksytel的配置文件(該配置文件中定義了相關的style規則)

完成配置後將添加的配置選爲默認配置,如圖


5Checkstyle使用

在工程上點擊右鍵,選擇「Checkstyle」選項,如圖

wps2B67.tmp

經常使用的選項爲「Activate Checkstyle」、「Check Code with Checkstyle」、「Clear Checkstyle violations」

其中「Activate Checkstyle」爲激活CheckStyle功能,在你編碼中會自動提示代碼的規範問題。(經測試通常是須要保存代碼後纔會有提示)

「Check Code with Checkstyle」表示代碼編寫完成後,統一驗證代碼相關規範問題。

「Clear Checkstyle violations」爲清楚相關的checkstyle提示信息

如圖爲相關提示信息

wps2B87.tmp

附:checkstyle.xml(來源於網絡)

<?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>
相關文章
相關標籤/搜索