java 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;
    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YD_1989

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值