instanceof
是 Java 的保留关键字,它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean
的数据类型
下面针对几种可能遇到的情况来看看会有什么结果:
可以看到, 这种情况下会有编译错误,那如果右边改为引用类型呢?
此时可以看到,仍然有编译错误,那么再试试特殊的 null
呢?
好像也不行,由此可以得出,基本类型不能用于 instanceof
判断.
对于 null
,我们可以看到它只能用来判断是否是引用类型,并且返回的总是 false
,表明它不是任意一个引用类型的对象实例.
它用来判断是否是基本类型或 null
的对象时,也会有编译错误,不可用.
我们创建如下关系的类和接口:
对于如下代码:
public class TestInstanceof {
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = new Animal();
Animal cat = new Cat();
System.out.println(dog instanceof Dog); // true
System.out.println(dog instanceof Bark); // true
System.out.println(animal instanceof Bark); // true
System.out.println(animal instanceof Dog); // false
System.out.println(cat instanceof Animal); // true
System.out.println(cat instanceof Cat); // true
System.out.println(dog instanceof Cat); // 编译错误
System.out.println(dog instanceof Integer); // 编译错误
System.out.println(dog instanceof int); // 编译错误
System.out.println(dog instanceof null); // 编译错误
}
}
instanceof
判断null
只能放在 instanceof
关键字的左边对引用类型示例稍加修改,可以得到数组类型用来判断时的情况:
public class TestInstanceof {
public static void main(String[] args) {
Dog[] dog = new Dog[3];
Animal animal = new Animal();
System.out.println(dog instanceof Dog[]); // true
System.out.println(dog instanceof Bark[]); // true
}
}
特别地,基本类型的数组也是可以用来判断的:
public class TestInstanceof {
public static void main(String[] args) {
int[] ary = new int[3];
System.out.println(ary instanceof int[]); // true
}
}
instanceof
关键字一般用于强制转换,在强转之前用它来判断是否可以强制转换:
public B convert(A a) {
if (a instanceof B) {
return (B) a;
}
return null;
}
用类似 Java 的伪代码来描述该原理如下所示:
boolean rs;
if (obj == null) {
rs= false;
} else {
try {
T temp = (T) obj;
rs= true;
} catch (ClassCastException e) {
rs = false;
}
}
return rs;
obj==null
,返回 false
obj
强制转换为 T
时发生编译错误,返回 false
T != null
,并且 (T) obj
不引发 ClassCastException
,返回 true
obj != null
并且 (T) obj
不引发 ClassCastException
,返回 true
,否则值为 false
总结:
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- stra.cn 版权所有 赣ICP备2024042791号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务