4

Java 16 新特性:instanceof增强

 2 years ago
source link: http://blog.didispace.com/java16-jep394-pattern-matching-for-instanceof/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Java 16 新特性:instanceof增强

instanceof这个关键词,主要用来判断某个对象是不是某个类的实例。

比如,有时候我们要处理一个类似这样的数据集:

Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);

这个Map中的Value值因为可能是不同的对象,所以定义的是Object。这个时候,当我们get出来的时候,就需要去判断和转换之后再去处理。

比如,我们取出key1value,然后截取一段字符串的操作,就需要这样写:

Object value  =data.get("key1");
if (value instanceof String) {
String s = (String) value;
System.out.println(s.substring(1));
}

先判断获取的value是否是String,再做强制类型转换,然后再对字符串进行操作。这是传统的写法,而在Java 16的增强之后,对于instanceof的判断以及类型转换可以合二为一了,所以改进后的写法可以如下:

Object value  =data.get("key1");
if (value instanceof String s) {
System.out.println(s.substring(1));
}

是不是简单不少呢?如果没用过的话,赶紧操作试试看吧!

Tips:该功能经历了2个Preview版本(JDK 14中的JEP 305、JDK 15中的JEP 375),最终定稿于JDK 16中的JEP 394。

如果您学习过程中如遇困难?可以加入我们超高质量的技术交流群,参与交流与讨论,更好的学习与进步!另外,不要走开,关注我!持续更新Java新特性专栏


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK