java中的instanceof关键字详细解读
instanceof关键字
instanceof 是 Java 的保留关键字,它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
代码中可能遇到的情况:
1、基本数据类型

如上图,这种情况会报错。将右边的类型改为引用类型:

依旧报错,改成特殊的null:

依旧报错,由此得出:基本类型不能用于 instanceof 判断。
为了验证这一点,换一个基本数据类型double进行测试:

依旧报错,可以验证结论正确。
2、引用类型
创建如下关系的类和接口:


测试一:
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = new Animal();
Animal cat = new Cat();
System.out.println("dog instanceof Dog的结果是:" + (dog instanceof Dog)); // true
System.out.println("dog instanceof Big的结果是:" + (dog instanceof Big)); // true
System.out.println("animal instanceof Big的结果是:" + (animal instanceof Big)); // true
System.out.println("animal instanceof Dog的结果是:" + (animal instanceof Dog)); // false
System.out.println("cat instanceof Animal的结果是:" + (cat instanceof Animal)); // true
System.out.println("cat instanceof Cat的结果是:" + (cat instanceof Cat)); // true
}打印结果:
dog instanceof Dog的结果是:true
dog instanceof Big的结果是:true
animal instanceof Big的结果是:true
animal instanceof Dog的结果是:false
cat instanceof Animal的结果是:true
cat instanceof Cat的结果是:true
测试二:

- 基本类型完全不能用于 instanceof 判断
- null 只能放在 instanceof 关键字的左边
3、数组类型
延续引用类型示例,可以得到数组类型用来判断时的情况:
Dog[] dog = new Dog[3];
Animal animal = new Animal();
System.out.println("dog instanceof Dog[]的打印结果是:"+(dog instanceof Dog[]));
System.out.println("dog instanceof Big[]的打印结果是:"+(dog instanceof Big[])); 打印结果:
dog instanceof Dog[]的打印结果是:true
dog instanceof Big[]的打印结果是:true
特别地,基本类型的数组也是可以用来判断的:
int[] arr = new int[3];
System.out.println("arr instanceof int[]的打印结果是:"+(arr instanceof int[]));
打印结果:
arr instanceof int[]的打印结果是:true
4、应用场景
instanceof 关键字一般用于强制转换,在强转之前用它来判断是否可以强制转换:
/**
*========================================
* @方法说明 : 空判断 空返回true
* @param obj
* @return boolean
* @exception
*========================================
*/
public static boolean isEmpty(Object obj) {
if (obj == null || "null".equals(obj.toString()) || "".equals(obj.toString())) {
return true;
}
if (obj instanceof String) {
return ((String) obj).trim().length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
return false;
}到此这篇关于java中的instanceof关键字详细解读的文章就介绍到这了,更多相关instanceof关键字内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java运算符与流程控制之全类型运算符用法及分支 / 循环语句实战指南
这篇文章主要介绍了Java运算符与流程控制之全类型运算符用法及分支/循环语句实战的相关资料,运算符包括算术、关系、逻辑、赋值和三元运算符,重点讲解了它们的用法、优先级和结合性,以及强制类型转换的注意事项,需要的朋友可以参考下2026-01-01
spring/springboot整合curator遇到的坑及解决
这篇文章主要介绍了spring/springboot整合curator遇到的坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-05-05
java中MultipartFile类型转为File类型的4种方法
Spring提供了一个MultipartFile接口来处理文件上传,但有时候我们需要将MultipartFile转换为File来进行一些特定的操作,比如保存文件到本地或者进行文件的处理等,这篇文章主要给大家介绍了关于java中MultipartFile类型转为File类型的4种方法,需要的朋友可以参考下2024-09-09
在CentOS7(有图形化界面)上安装maven和idea的详细教程
这篇文章主要介绍了在CentOS7(有图形化界面)上安装maven和idea的详细教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-03-03


最新评论