instanceof关键字

来源:互联网 发布:php建站源码 编辑:程序博客网 时间:2024/06/06 18:14

这个关键字的作用是:在运行时,左边的对象是否是右边类的实例?
例:

    InstanceofTest instanceofTest = new InstanceofTest();    System.out.println(instanceofTest instanceof Object);

这两句的返回结果,很明显,应该是true。

instanceof同样可以判断数组类型的对象。

int[] arr =  new int[]{};System.out.println(arr instanceof int[]);

返回结果true。
看到有些博客讲,instanceof左边的对象不能为null,否则会报NullPointException,我试了一下,并没有。

String str =null;System.out.println(null instanceof Object);InstanceofTest nullTest = null;System.out.println(nullTest instanceof Object);

这里写图片描述

我们之前提到了,instanceof关键字是在运行时判断。
这里写图片描述

我们可以发现,我们在编译期就可以发现错误,判断类型,所以说是在运行时判断。

0 0