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());
}

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

教程推荐

前端全链路优化实战课 -〔唐俊开〕

B端产品经理入门课 -〔董小圣〕

超级访谈:对话玉伯 -〔玉伯〕

分布式金融架构课 -〔任杰〕

Selenium自动化测试实战 -〔郭宏志〕

后端存储实战课 -〔李玥〕

后端技术面试 38 讲 -〔李智慧〕

消息队列高手课 -〔李玥〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

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