JDK23中的instanceof

前言

JDK23以前版本,instanceof关键字是不支持拓展基本类型,允许在所有模式上下文中使用原始类型,包括 longfloatdoubleboolean等,但目前是预览属性

instanceof使用

JDK23以前是这么使用的,要使用引用类型

typescript 复制代码
public class Instanceof1Demo {


    public static void main(String[] args) {
        Object data = 1;
        if (data instanceof Integer) {
            System.out.println(data);
        } else {
            System.out.println(2);
        }
    }
}

输出结果为

使用JDK23中的instanceof要先开启预览属性

typescript 复制代码
public class Instanceof1Demo {


    public static void main(String[] args) {
        Object data = 1;
        if (data instanceof int str) {
            System.out.println(str);
        } else {
            System.out.println(2);
        }
    }
}

输出结果为

总结

JDK23中,JEP 455 的预览特性中,instanceof 全面支持所有原始类型,包括 byte, short, char, int, long, float, double, boolean,但是属于预览属性,没有转正,使不使用就看个人选择

相关推荐
sakoba6 分钟前
spring IOC(实现原理)
java·开发语言
人生偌只如初见10 分钟前
NebulaGraph学习笔记-SessionPool之getSession
java·graph·nebula·session·pool
五行星辰12 分钟前
SpringBoot与Redis联姻:从青铜到王者的配置婚庆指南!
java·后端
牛肉汤16 分钟前
联邦式架构中的协议抉择:从 Mastodon 的设计看分布式系统的技术权衡
后端
小园子的小菜19 分钟前
探秘 Netty 通信中的 SslHandler 类:保障网络通信安全的基石
java·安全·web安全·netty
吹风的坚果20 分钟前
HTTPS的那些事
后端·https
五行星辰23 分钟前
Redisson:Redis界的变形金刚,会变身还会唱跳Rap!
java·后端
BUG研究员_24 分钟前
Spring Boot自动装配原理
java·spring boot·后端
嘵奇25 分钟前
MyBatis-Plus 注解大全
java·mybatis
L7ink25 分钟前
FinBot - WeChatFerry + DeepSeek打造 个人智能记账助手
后端·deepseek