你真的了解Java中的Instanceof吗?

来源:互联网 发布:大众软件2014电子版 编辑:程序博客网 时间:2024/06/05 21:04

转自 http://blog.csdn.net/iceIcold/article/details/51933359

instanceof 是一个简单的二元操作符, 它是用来判断一个对象是否是一个类实例的


boolean b1 = "Sting" instanceof Object;
b1为true 因为String是Object的子类


boolean b2 = new String() instanceof String;
b2为true


boolean b3 = new Object() instanceof String;
b3为false Object是父类


boolean b4 = 'A' instanceof Character;
编译不通过 ‘A’在此处视为基本数据类型char,instanceof操作符只能用作对象的判断


boolean b5 = null instanceof String;
b5为false 这是instanceof 特 有 的 规 则 : 若左操作数为null, 结果就直接返回false, 不再运算右操作数是什么类。


boolean b6 = (String)null instanceof String;
b6为false 即使类型转换还是个 null


boolean b7 = new Date() instanceof String;
编译不通过 instanceof 操作符的左右操作数必须有继承或实现关系,否则编译出错


boolean b8 = new GenericClass<String>().isDateInstance("");
class GenericClass<T>{
public boolean isDateInstance(T t){
return t instanceof Date;
}

编译通过,b8为false 因为用了泛型,所以字节码的时候T就是Object类型啦,此处t instanceof Date等价于Object instance of Date。

原创粉丝点击