1. 程式人生 > >eclipse中checkstyle的安裝使用

eclipse中checkstyle的安裝使用

  checkstyle是程式碼格式檢查工具,根據已經設定好的編碼規則(一個xml檔案)來自動檢查程式碼,比如:方法的行數、方法和變數的命名等。目的是規範程式碼,通俗點講就是讓程式碼看起來像一個人寫的。

下面講下如何使用這個工具。

一、工具安裝

  方式一:

  window --> preferences,沒有安裝checkstyle的時候這個彈出如下:

  

 

 開啟eclipse, help->Install New Software...    然後填入:CheckStyle - http://eclipse-cs.sourceforge.NET/update

 

選中上圖的兩個檔案,依次點選 Next -->Next,選中I accept .....,Finish

 

點選Install anyway 

 

點選重啟,生效。 

 

再次開啟 Preferences這個彈窗

以上是在eclipse 4.9.0 + jdk1.8.0_181的下安裝工具的過程,但是,不是所有環境都能按照以上按照方法解決的。比如,在eclipse4.2.0 + jdk1.7.0_45的環境下,按照以上方式去安裝,Preferences彈窗沒有checkstyle顯示。

可以嘗試下下面的方法

方式二:

下載:https://files.cnblogs.com/files/sucb/checkstyle-5.6.1.rar

開啟eclipse安裝路徑,然後新建一個資料夾checkstyle(資料夾名字可以隨意取),然後將下載檔案中的features和plugins資料夾拷貝過來,如下圖所示

 

然後在eclipse安裝目錄的檔案下  新建一個txt檔案,比如checkstyle.txt(這個檔名字也是可以隨意取),.txt修改為.link,加入path=D:\\(wjhl)eclipse-juno-with-toolset\\checkstyle,這個路徑是新建checkstyle的路徑,注意是兩個\

 

然後重新開啟eclipse的Preferences彈窗,如下所示

 

如果這兩種方式都沒有效果,可以在網上找下其他的安裝方式。

 

二、匯入checkstyle的規範

規範檔案是一個xml檔案,沒有的話,可以使用以下檔案或者在網上找一個,然後根據自己公司的規範略加修改,比如:我建了一個company-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="2000"/>        
  </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="eol"/>
    </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,50}$)"/>    
    </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,50}$)"/>     
    </module>
    
    <!-- methods -->  
    <module name="MethodName">          
      <property name="format" value="(^[a-z][a-zA-Z0-9]{0,50}$)"/>         
    </module> 
    
    <!-- non-static fields -->
    <module name="MemberName">  
        <property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,50}$)"/>         
    </module>
    
    <!-- parameters -->
    <module name="ParameterName">
        <property name="format" value="(^[a-z][a-zA-Z0-9_]{0,50}$)"/>         
    </module>
    
    <!-- constants (static,  final fields) -->
    <module name="ConstantName"> 
        <property name="format" value="(^[A-Z0-9_]{0,50}$)"/>      
    </module>
    
    <!-- 程式碼縮排   -->
    <module name="Indentation">
            <property name="basicOffset" value="4"/>
    </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="7"/>              
    </module>
    
    <!-- 每行字元數 -->    
    <module name="LineLength">  
      <property name="max" value="120"/>       
    </module>  
    
    <!-- Checks for long methods and constructors. max default 300行. 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巢狀語句個數 最多2層 -->
    <module name="NestedIfDepth">        
      <property name="max" value="2"/>         
    </module>  
    
    <!-- try-catch 巢狀語句個數 最多2層 -->
    <module name="NestedTryDepth">  
      <property name="max" value="2"/>         
    </module>  
    
    <!-- 禁止使用System.out.println -->  
    <module name="Regexp">  
        <property name="format" value="System\.out\.println" />  
        <property name="illegalPattern" value="true"/>  
        <property name="ignoreComments" value="true" />  
    </module>  
     
    <!-- 返回個數 
    <module name="ReturnCount">        
      <property name="max" value="5"/>  
      <property name="format" value="^$"/>          
    </module>                  
  -->   
  </module>
  
</module>
View Code

 

將規範檔案放到某個路徑下,比如放到eclipse的工作空間下

 

開啟eclipse,新建一個規範的配置,如下所示

 

配置checkstyle,點OK後彈出窗確定即可

啟動配置

 右鍵專案 --> properties --> Checkstyle

 

 也可以右鍵專案 -->然後找到Checkstyle的標籤,選中後出現二級選單,

舉個例子:

加上註解後

 

eclipse的一些設定,可以參考下:https://www.cnblogs.com/sucb/p/9459435.html