CheckStyle 是靜態代碼分析工具,依據配置規則(如 Google、Sun、自定義)檢查 Java 代碼風格、命名、佈局、Javadoc 等,強制團隊統一編碼標準。Eclipse 整合後可即時標記違規,亦可整合 Maven/Gradle/CI 流程。
Help → Install New Software → Add。CheckStyle,Location: https://eclipse-cs.sf.net/update/(或 SourceForge 下載離線包)。CheckStyle 全選安裝,接受授權,重啟 IDE。CheckStyle → Check Code with CheckStyle。Properties → CheckStyle 勾選 CheckStyle active for this project。New → File from file system 選取 checkstyle.xml(可從 Google Style、Sun Checks 下載並微調)。Real-time check(即時檢查較耗資源),改用手動或 Save Actions 觸發。| 違規提示 | 含義 | 快速修復 |
|---|---|---|
| Line contains a tab character | 含 Tab 字符 | Preferences → General → Editors → Text Editors 勾選 Insert spaces for tabs;Java → Code Style → Formatter → Tab policy: Spaces only;XML/JS/CS 同理。再 Ctrl+Shift+F 格式化。 |
| Line longer than 80/120 characters | 行超長 | 拆行、提取變數、調整 Formatter Maximum line width。 |
| Missing a Javadoc comment | 類/方法/欄位缺 Javadoc | 補全 /** ... */,含 @param @return @throws。 |
| "{" should be on the previous line | 左大括號應在上一行 | Formatter → Braces → Same line。 |
| "}" should be on the same line | 右大括號應與下句同行 | Formatter → Braces → Next line 對應調整。 |
| Parameter 'X' should be final | 參數建議 final | 加 final 或關閉規則 ParameterAssignment。 |
| Redundant 'public' modifier | 介面方法多餘 public | 介面方法隱含 public,刪除。 |
| Variable 'X' must be private and have accessor methods | 欄位需私有並提供 getter/setter | 改 private + 生成存取器(Lombok @Getter/@Setter)。 |
| Magic number | 硬編碼數字(非 -1,0,1,2) | 提取為 private static final 常數並命名。 |
| Unused import | 未使用的 import | Ctrl+Shift+O 自動整理。 |
| Avoid using the ".*" form of import | 禁止星號導入 | Formatter → Organize Imports → Number of imports needed for .* 設大值或手動展開。 |
| Final modifier out of order | 修飾符順序錯誤 | 標準順序:public/protected/private → static → final → transient → volatile。 |
| Got an exception - Unexpected character 0xfffd | 編碼不匹配 | CheckStyle 配置加 <property name="charset" value="UTF-8"/>;專案/檔案編碼統一 UTF-8。 |
| File does not end with a newline | 檔案未以換行結尾 | IDE 設定 Insert newline at end of file 或重建檔案。 |
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError> <!-- 違規即建構失敗 -->
</configuration>
<executions>
<execution><phase>validate</phase><goals><goal>check</goal></goals></execution>
</executions>
</plugin>
checkstyle.xml(基於 Google Style 微調),納入版控。.epf / formatter.xml),Ctrl+Shift+F 即可修復 90% 佈局問題。SpotBugs、PMD 互補:CheckStyle 管風格,SpotBugs 管缺陷,PMD 管慣用模式。