Lombok `@ExtensionMethod` 讓 Java 程式碼優雅變身
告別冗長的工具類呼叫:用 Lombok @ExtensionMethod 讓 Java 程式碼優雅變身 身為 Java 開發者,我們都寫過或看過這樣的程式碼: String userInput = " hello world " ; if ( ! StringUtils . isBlank ( userInput ) ) { String processedText = StringUtils . capitalize ( userInput . trim ( ) ) ; System . out . println ( processedText ) ; } int value = NumberUtils . toInt ( someString , 0 ) ; // 失敗時返回預設值 0 這段程式碼完全沒問題,功能正常、邏輯清晰。 StringUtils 和 NumberUtils 。但你不禁會想:如果程式碼能讀起來更像自然語言,更符合物件導向的思維,那該有多好? 如果能像 C# 或 Kotlin 那樣,寫成這樣呢? // 理想中的程式碼 String userInput = " hello world " ; if ( ! userInput . isBlank ( ) ) { // String 本身就有 isBlank() String processedText = userInput . trim ( ) . capitalize ( ) ; // 如果能鏈式呼叫就更棒了! System . out . println ( processedText ) ; } int value = someString . toInt ( 0 ) ; 這就是「擴充方法」(Extension Methods) 的魅力所在。它允許我們在不修改原始類別的情況下,為其「添加」新方法。雖然 Java 語言本身不直接支援此功能,但我們有好朋友 Lombok !透過它的 @ExtensionMethod 註解,我們幾乎可以完美地實現這個夢想。 步驟 2:建立你的「擴充方法」容器 首先...