Groovy 是運行在 JVM 上的動態語言,與 Java 無縫互操作,語法更簡潔、表達力更強。對 Java 開發者,學習 Groovy 不僅能提升腳本編寫、測試、構建腳本效率,更能通過閉包、元編程等特性拓寬編程視野。本文針對 Java 開發者,梳理從 Java 風格遷移到 Groovy 風格的關鍵點。
| 特性 | Java | Groovy | 說明 |
|---|---|---|---|
| 分號 | 必需 | 可選 (行尾自動推斷) | 建議省略 |
| return | 必需 (void 除外) | 可選 (最後一句表達式值) | 隱式返回 |
| 類型聲明 | 強制 | 可選 (def / 具體類型) | 建議公共 API 用強類型 |
| 訪問修飾符 | 默認 package-private | 默認 public | 省略 public |
| 括號 | 調用必需 | 頂層調用可省略 | println "hi" |
| Getter/Setter | 手寫/IDE 生成 | 屬性自動生成 (POGO) | class Person { String name } |
| 字符串插值 | "a=" + a | "a=${a}" (GString) | 雙引號才插值 |
| 集合字面量 | new ArrayList() | [1,2,3] / [k:v] | 原生語法 |
| 安全導航 | 手動 null 判斷 | obj?.prop?.method() | 避免 NPE |
| Elvis 操作符 | a != null ? a : b | a ?: b | 默認值賦值 |
// 定義閉包
def greet = { name -> println "Hello, $name!" }
greet("Groovy") // Hello, Groovy!
// 隱式參數 it (單參數)
[1,2,3].each { println it * 2 }
// 集合操作鏈
def list = [1,2,3,4,5,6,7,8,9,10]
def result = list.findAll { it % 2 == 0 } // [2,4,6,8,10]
.collect { it * 10 } // [20,40,60,80,100]
.sum() // 300
// with() 簡化對象配置
def server = new Server()
server.with {
name = "AppServer"
port = 8080
start()
}
// List
def nums = [1, 3, 5, 7]
nums << 9 // 添加
assert 5 in nums // 包含判斷
assert nums[1] == 3 // 索引訪問
nums[1] = 4 // 修改
// Map (鍵默認 String)
def map = [name: 'Groovy', version: 4.0]
map.language = 'JVM' // 屬性訪問 = put
assert map.name == 'Groovy'
map << [since: 2003] // 批量添加
// Range
def range = 1..10 // 包含端點
def rangeEx = 1..<10 // 不含端點
assert 5 in range
(1..3).each { print it } // 123
def x = 1.23
def result = switch(x) {
case "foo" -> "string"
case 12..30 -> "range"
case [4,5,6] -> "list"
case Integer -> "integer"
case Number -> "number" // 命中:1.23 是 Number
default -> "other"
}
assert result == "number"
import java.util.List as JList
import java.awt.List as AList
import java.awt.WindowConstants as WC
import static java.lang.Math.PI as π
import static com.utils.StringUtils.* as StrUtils
所有對象可作為布爾值判斷:
false:null、false、空集合/字符串/Map、0、空 Matchertrue:其他所有// 替代 if (str != null && !str.isEmpty())
if (str) { ... }
// 自定義真值
class MyClass {
boolean asBoolean() { return this.value > 0 }
}
def x = 1, y = 2
assert x + y == 3
// 失敗時輸出詳細表達式值圖譜:
// assert x + y == 4
// | | |
// 1 2 3
// 捕獲任意異常
try { risky() } catch (any) { log.error("忽略異常") }
// 單行 try-with-resources (Groovy 3+)
new File('a.txt').withReader { r -> println r.readLine() }
def 或省略類型,追求簡潔@CompileStatic 獲得性能與類型安全groovysh / groovyConsole@CompileStaticGroovy 不只是「簡化語法的 Java」,更是一套以閉包、元編程、動態特性為核心的表達式語言。掌握其風格精髓——少寫樣板碼,多用集合操作鏈,善用閉包抽象控制流,信任 Groovy Truth——能讓你在 JVM 生態中靈活選擇最適合的工具解決問題。