Java14instanceof

Java14instanceof 首页 / Java入门教程 / Java14instanceof

了解 instanceof 的模式匹配以及如何使用它从Java 14开始( JEP 305 )。这是JDK 14中的预览语言函数

如果应用程序需要处理某种类型的类,但是无涯教程有超类类型的引用,那么需要检查该实例的类型并进行适当的转换。

例如,Customer的类型可以为BusinessCustomerPersonalCustomer。根据客户实例的类型,可以根据上下文获取信息。

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
}

如果objString的实例,则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());
}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

云原生基础架构实战课 -〔潘野〕

大型Android系统重构实战 -〔黄俊彬〕

说透区块链 -〔自游〕

数据中台实战课 -〔郭忆〕

RPC实战与核心原理 -〔何小锋〕

安全攻防技能30讲 -〔何为舟〕

高并发系统设计40问 -〔唐扬〕

全栈工程师修炼指南 -〔熊燚(四火)〕

邱岳的产品实战 -〔邱岳〕

好记忆不如烂笔头。留下您的足迹吧 :)