了解 instanceof 的模式匹配以及如何使用它从Java 14开始( JEP 305 )。这是JDK 14中的预览语言函数。
如果应用程序需要处理某种类型的类,但是无涯教程有超类类型的引用,那么需要检查该实例的类型并进行适当的转换。
例如,Customer
的类型可以为BusinessCustomer
或PersonalCustomer
。根据客户实例的类型,可以根据上下文获取信息。
Customer customer = null; //get this value from some method String customerName = ""; //Old approach if(customer instanceof PersonalCustomer) { PersonalCustomer pCustomer = (PersonalCustomer) customer; //Redundant casting customerName = String.join(" ", pCustomer.getFirstName(), pCustomer.getMiddleName(), pCustomer.getLastName()); } else if(customer instanceof BusinessCustomer) { BusinessCustomer bCustomer = (BusinessCustomer) customer; //Redundant casting customerName = bCustomer.getLegalName(); }
现在,通过与instanceof匹配的模式,可以按以下方式编写类似的代码。在这里,可以减少类型转换的样板代码(例如,将pCustomer
强制转换为customer
)。
//New approach if(customer instanceof PersonalCustomer pCustomer) { customerName = String.join(" ", pCustomer.getFirstName(), pCustomer.getMiddleName(), pCustomer.getLastName()); } else if(customer instanceof BusinessCustomer bCustomer) { customerName = bCustomer.getLegalName(); }
在下面的代码中,短语String s
是类型测试模式:
if (obj instanceof String s) { //can use s here } else { //can't use s here }
如果obj
是String
的实例,则instanceof
运算符会将目标obj
与类型测试模式匹配,然后将其强制转换为String
并分配给绑定变量s
请注意,如果obj为非null
,则仅匹配模式,并且仅分配s
。
例如,当无涯教程添加&&运算符和另一个语句时,仅当instanceof成功并将其分配给pCustomer时,才会评估添加的语句。此外,true块中的pCustomer引用了封闭类中的一个字段。
//Works fine if(customer instanceof PersonalCustomer pCustomer && pCustomer.getId() > 0) { customerName = String.join(" ", pCustomer.getFirstName(), pCustomer.getMiddleName(), pCustomer.getLastName()); }
与上述情况相反,当添加||
运算符和另一条语句时,绑定变量pCustomer
不在||
运算符,它也不在true块的范围内。此时的pCustomer
引用了封闭类中的一个字段。
//Compiler error ::The pattern variable pCustomer is not in scope in this location if(customer instanceof PersonalCustomer pCustomer || pCustomer.getId() > 0) { customerName = String.join(" ", pCustomer.getFirstName(), pCustomer.getMiddleName(), pCustomer.getLastName()); }
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)