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顯示。

原因是自動安裝的checkstyle工具對jdk的版本有要求,參考下:https://checkstyle.org/eclipse-cs/#!/releasenotes

可以嘗試下下面的方法

方式二:

下載鏈接:https://pan.baidu.com/s/19MvBjoxdKljkA9m-vFab-g 
提取碼:dt87 

打開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文件,內容如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.2//EN" "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
  3. <!-- Generated by RHY @will_awoke -->
  4. <module name="Checker">
  5. <property name="charset" value="UTF-8"/>
  6. <property name="severity" value="warning"/>
  7. <!-- Checks for Size Violations. -->
  8. <!-- 檢查文件的長度(行) default max=2000 -->
  9. <module name="FileLength">
  10. <property name="max" value="2000"/>
  11. </module>
  12. <!-- Checks that property files contain the same keys. -->
  13. <!-- 檢查**.properties配置文件 是否有相同的key
  14. <module name="Translation">
  15. </module>
  16. -->
  17. <module name="TreeWalker">
  18. <!-- Checks for imports -->
  19. <!-- 必須導入類的完整路徑,即不能使用*導入所需的類 -->
  20. <module name="AvoidStarImport"/>
  21. <!-- 檢查是否從非法的包中導入了類 illegalPkgs: 定義非法的包名稱-->
  22. <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
  23. <!-- 檢查是否導入了不必顯示導入的類-->
  24. <module name="RedundantImport"/>
  25. <!-- 檢查是否導入的包沒有使用-->
  26. <module name="UnusedImports"/>
  27. <!-- Checks for whitespace
  28. <module name="EmptyForIteratorPad"/>
  29. <module name="MethodParamPad"/>
  30. <module name="NoWhitespaceAfter"/>
  31. <module name="NoWhitespaceBefore"/>
  32. <module name="OperatorWrap"/>
  33. <module name="ParenPad"/>
  34. <module name="TypecastParenPad"/>
  35. <module name="WhitespaceAfter"/>
  36. <module name="WhitespaceAround"/>
  37. -->
  38. <!-- 檢查類和接口的javadoc 默認不檢查author 和version tags
  39. authorFormat: 檢查author標籤的格式
  40. versionFormat: 檢查version標籤的格式
  41. scope: 可以檢查的類的範圍,例如:public只能檢查public修飾的類,private可以檢查所有的類
  42. excludeScope: 不能檢查的類的範圍,例如:public,public的類將不被檢查,但訪問權限小於public的類仍然會檢查,其他的權限以此類推
  43. tokens: 該屬性適用的類型,例如:CLASS_DEF,INTERFACE_DEF
  44. <module name="JavadocType">
  45. <property name="authorFormat" value="\S"/>
  46. <property name="scope" value="protected"/>
  47. <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>
  48. </module>
  49. -->
  50. <!-- 檢查方法的javadoc的註釋
  51. scope: 可以檢查的方法的範圍,例如:public只能檢查public修飾的方法,private可以檢查所有的方法
  52. allowMissingParamTags: 是否忽略對參數註釋的檢查
  53. allowMissingThrowsTags: 是否忽略對throws註釋的檢查
  54. allowMissingReturnTag: 是否忽略對return註釋的檢查 -->
  55. <module name="JavadocMethod">
  56. <property name="scope" value="private"/>
  57. <property name="allowMissingParamTags" value="false"/>
  58. <property name="allowMissingThrowsTags" value="false"/>
  59. <property name="allowMissingReturnTag" value="false"/>
  60. <property name="tokens" value="METHOD_DEF"/>
  61. <property name="allowUndeclaredRTE" value="true"/>
  62. <property name="allowThrowsTagsForSubclasses" value="true"/>
  63. <!--允許get set 方法沒有註釋-->
  64. <property name="allowMissingPropertyJavadoc" value="true"/>
  65. </module>
  66. <!-- 檢查類變量的註釋
  67. scope: 檢查變量的範圍,例如:public只能檢查public修飾的變量,private可以檢查所有的變量 -->
  68. <module name="JavadocVariable">
  69. <property name="scope" value="private"/>
  70. </module>
  71. <!--option: 定義左大括號'{'顯示位置,eol在同一行顯示,nl在下一行顯示
  72. maxLineLength: 大括號'{'所在行行最多容納的字符數
  73. tokens: 該屬性適用的類型,例:CLASS_DEF,INTERFACE_DEF,METHOD_DEF,CTOR_DEF -->
  74. <module name="LeftCurly">
  75. <property name="option" value="eol"/>
  76. </module>
  77. <!-- NeedBraces 檢查是否應該使用括號的地方沒有加括號
  78. tokens: 定義檢查的類型 -->
  79. <module name="NeedBraces"/>
  80. <!-- Checks the placement of right curly braces ('}') for else, try, and catch tokens. The policy to verify is specified using property option.
  81. option: 右大括號是否單獨一行顯示
  82. tokens: 定義檢查的類型
  83. <module name="RightCurly">
  84. <property name="option" value="alone"/>
  85. </module>
  86. -->
  87. <!-- 檢查在重寫了equals方法後是否重寫了hashCode方法 -->
  88. <module name="EqualsHashCode"/>
  89. <!-- Checks for illegal instantiations where a factory method is preferred.
  90. Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.
  91. 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().
  92. 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. -->
  93. <module name="IllegalInstantiation">
  94. <property name="classes" value="java.lang.Boolean"/>
  95. </module>
  96. <!-- Checks for Naming Conventions. 命名規範 -->
  97. <!-- local, final variables, including catch parameters -->
  98. <module name="LocalFinalVariableName"/>
  99. <!-- local, non-final variables, including catch parameters-->
  100. <module name="LocalVariableName"/>
  101. <!-- static, non-final fields -->
  102. <module name="StaticVariableName">
  103. <property name="format" value="(^[A-Z0-9_]{0,50}$)"/>
  104. </module>
  105. <!-- packages -->
  106. <module name="PackageName" >
  107. <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
  108. </module>
  109. <!-- classes and interfaces -->
  110. <module name="TypeName">
  111. <property name="format" value="(^[A-Z][a-zA-Z0-9]{0,50}$)"/>
  112. </module>
  113. <!-- methods -->
  114. <module name="MethodName">
  115. <property name="format" value="(^[a-z][a-zA-Z0-9]{0,50}$)"/>
  116. </module>
  117. <!-- non-static fields -->
  118. <module name="MemberName">
  119. <property name="format" value="(^[a-z][a-z0-9][a-zA-Z0-9]{0,50}$)"/>
  120. </module>
  121. <!-- parameters -->
  122. <module name="ParameterName">
  123. <property name="format" value="(^[a-z][a-zA-Z0-9_]{0,50}$)"/>
  124. </module>
  125. <!-- constants (static, final fields) -->
  126. <module name="ConstantName">
  127. <property name="format" value="(^[A-Z0-9_]{0,50}$)"/>
  128. </module>
  129. <!-- 代碼縮進 -->
  130. <module name="Indentation">
  131. <property name="basicOffset" value="4"/>
  132. </module>
  133. <!-- Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
  134. 檢查是否拋出了多餘的異常
  135. <module name="RedundantThrows">
  136. <property name="logLoadErrors" value="true"/>
  137. <property name="suppressLoadErrors" value="true"/>
  138. </module>
  139. -->
  140. <!-- Checks for overly complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc.
  141. 檢查boolean值是否冗餘的地方
  142. Rationale: Complex boolean logic makes code hard to understand and maintain. -->
  143. <module name="SimplifyBooleanExpression"/>
  144. <!-- Checks for overly complicated boolean return statements. For example the following code
  145. 檢查是否存在過度複雜的boolean返回值
  146. if (valid())
  147. return false;
  148. else
  149. return true;
  150. could be written as
  151. return !valid();
  152. The Idea for this Check has been shamelessly stolen from the equivalent PMD rule. -->
  153. <module name="SimplifyBooleanReturn"/>
  154. <!-- Checks that a class which has only private constructors is declared as final.只有私有構造器的類必須聲明爲final-->
  155. <module name="FinalClass"/>
  156. <!-- Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.
  157. 確保Utils類(只提供static方法和屬性的類)沒有public構造器。
  158. 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.
  159. If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:
  160. public class StringUtils // not final to allow subclassing
  161. {
  162. protected StringUtils() {
  163. throw new UnsupportedOperationException(); // prevents calls from subclass
  164. }
  165. public static int count(char c, String s) {
  166. // ...
  167. }
  168. } -->
  169. <module name="HideUtilityClassConstructor"/>
  170. <!-- 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.
  171. 檢查class成員屬性可見性。只有static final 修飾的成員是可以public的。其他的成員屬性必需是private的,除非屬性protectedAllowed或者packageAllowed設置了true.
  172. 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.
  173. Rationale: Enforce encapsulation. 強制封裝 -->
  174. <module name="VisibilityModifier"/>
  175. <!-- 每一行只能定義一個變量 -->
  176. <module name="MultipleVariableDeclarations">
  177. </module>
  178. <!-- 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[])
  179. 檢查再定義數組時,採用java風格還是c風格,例如:int[] num是java風格,int num[]是c風格。默認是java風格-->
  180. <module name="ArrayTypeStyle">
  181. </module>
  182. <!-- 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.
  183. <module name="MagicNumber">
  184. </module>
  185. -->
  186. <!-- 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.
  187. 檢查是否存在TODO(待處理) TODO是javaIDE自動生成的。一般代碼寫完後要去掉。
  188. -->
  189. <module name="TodoComment"/>
  190. <!-- 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.
  191. 檢查是否在long類型是否定義了大寫的L.字母小寫l和數字1(一)很相似。
  192. looks a lot like 1. -->
  193. <module name="UpperEll"/>
  194. <!-- Checks that switch statement has "default" clause. 檢查switch語句是否有‘default’從句
  195. Rationale: It's usually a good idea to introduce a default case in every switch statement.
  196. Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch,
  197. 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. -->
  198. <module name="MissingSwitchDefault"/>
  199. <!--檢查switch中case後是否加入了跳出語句,例如:return、break、throw、continue -->
  200. <module name="FallThrough"/>
  201. <!-- Checks the number of parameters of a method or constructor. max default 7個. -->
  202. <module name="ParameterNumber">
  203. <property name="max" value="7"/>
  204. </module>
  205. <!-- 每行字符數 -->
  206. <module name="LineLength">
  207. <property name="max" value="120"/>
  208. </module>
  209. <!-- Checks for long methods and constructors. max default 300行. max=300 設置長度300 -->
  210. <module name="MethodLength">
  211. <property name="max" value="300"/>
  212. </module>
  213. <!-- ModifierOrder 檢查修飾符的順序,默認是 public,protected,private,abstract,static,final,transient,volatile,synchronized,native -->
  214. <module name="ModifierOrder">
  215. </module>
  216. <!-- 檢查是否有多餘的修飾符,例如:接口中的方法不必使用public、abstract修飾 -->
  217. <module name="RedundantModifier">
  218. </module>
  219. <!--- 字符串比較必須使用 equals() -->
  220. <module name="StringLiteralEquality">
  221. </module>
  222. <!-- if-else嵌套語句個數 最多2層 -->
  223. <module name="NestedIfDepth">
  224. <property name="max" value="2"/>
  225. </module>
  226. <!-- try-catch 嵌套語句個數 最多2層 -->
  227. <module name="NestedTryDepth">
  228. <property name="max" value="2"/>
  229. </module>
  230. <!-- 禁止使用System.out.println -->
  231. <module name="Regexp">
  232. <property name="format" value="System\.out\.println" />
  233. <property name="illegalPattern" value="true"/>
  234. <property name="ignoreComments" value="true" />
  235. </module>
  236. <!-- 返回個數
  237. <module name="ReturnCount">
  238. <property name="max" value="5"/>
  239. <property name="format" value="^$"/>
  240. </module>
  241. -->
  242. </module>
  243. </module>

 

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

 

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

 

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

啓動配置

 右鍵項目 --> properties --> Checkstyle

 

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

舉個例子:

加上註解後

 

轉載:https://blog.csdn.net/suchenbin/article/details/83870233

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章