Java 14引入了pattern Matching for instanceof (另一种预览语言功能) ,从而消除了在使用instanceof
时进行强制转换的需要。 例如,考虑以下代码:
if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); }
该代码现在可以重写为:
if (obj instanceof String s) { System.out.println(s.length()); }
如上所示, instanceof
运算符现在使用“绑定变量”,并且不再需要强制转换为String
。 如果obj
是String
的实例,则将其强制转换为String
并分配给绑定变量s
。 绑定变量仅在if语句的true块的范围内。
特别是,此功能使equals
方法更加简洁,如下例所示:
@Override public boolean equals(Object obj) { return this == obj || (obj Person other) && other.name.equals(name); (obj instanceof Person other) && other.name.equals(name); }
此功能是模式匹配的一个示例,该模式已经在许多其他编程语言中提供,并且允许我们有条件地从对象中提取组件。 它为将来更广泛的模式匹配打开了大门,我对此感到非常兴奋!
翻译自: https://www.javacodegeeks.com/2020/04/java-14-pattern-matching-for-instanceof.html