你真的了解Java中的Instanceof吗?

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值