详解 Java 17 中的模式匹配(Pattern Matching)
詳解 Java 17 中的模式匹配(Pattern Matching)
提到模式匹配(Pattern Matching) ,Java 開發(fā)人員可能會比較陌生。實(shí)際上,其他編程語言的開發(fā)人員早就已經(jīng)使用過模式匹配了 。JVM 上的編程語言 Scala 的模式匹配功能就很強(qiáng)大。
什么是模式匹配?
為了更好地解釋模式匹配,我們從一個簡單的例子開始。我們希望創(chuàng)建一個方法 ,可以把任何對象轉(zhuǎn)換成 String 格式。這就需要根據(jù)對象的類型來進(jìn)行不同的格式化操作。我們可以很容易就寫出下面這樣的代碼。這段代碼的核心是使用 instanceof 操作符來檢查輸入對象的類型,再根據(jù)對象類型進(jìn)行格式化操作。
public class ObjectFormatter { public String format(Object input) { if (input == null) { return ""; } else if (input instanceof Number) { return NumberFormat.getNumberInstance().format(input); } else if (input instanceof LocalDateTime) { return ((LocalDateTime) input).format(DateTimeFormatter.ISO_DATE_TIME); } else { return input.toString(); } }}上述對 instanceof 操作符的使用就是模式匹配的一種簡單形式。
一個模式由匹配 predicate 和模式變量的集合組成。
- 匹配 predicate 判斷一個模式是否可以匹配目標(biāo)對象。
- 如果模式匹配的話 ,模式變量的集合用來從目標(biāo)對象中提取值 。
在 instanceof 操作符的例子中 ,匹配 predicate 的作用是檢查目標(biāo)對象的類型 ,而模式變量的集合中只有一個變量,就是目標(biāo)對象自身