Java14 - instanceof

Java14 - instanceof 首页 / Java入门教程 / Java14 - instanceof

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

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

技术教程推荐

技术领导力实战笔记 -〔TGO鲲鹏会〕

白话法律42讲 -〔周甲徳〕

Nginx核心知识150讲 -〔陶辉〕

编译原理之美 -〔宫文学〕

现代C++编程实战 -〔吴咏炜〕

SRE实战手册 -〔赵成〕

Kafka核心源码解读 -〔胡夕〕

Go 语言项目开发实战 -〔孔令飞〕

手把手带你写一个MiniSpring -〔郭屹〕

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