instanceof关键字

instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例,用法为:

boolean result = obj instanceof Class

其中 obj 为一个对象,Class 表示一个类或者一个接口,当 obj 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。

注意:编译器会检查 obj 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。

1、obj 必须为引用类型,不能是基本类型

int i = 0;
System.out.println(i instanceof Integer);//编译不通过
System.out.println(i instanceof Object);//编译不通过

instanceof 运算符只能用作对象的判断。

2、obj 为 null

	
System.out.println(null instanceof Object);//false

3、obj 为 class 类的实例对象

Integer integer = new Integer(1);
System.out.println(integer instanceof  Integer);//true

4.obj 为 class 接口的实现类

我们可以用 instanceof 运算符判断 某个对象是否是 List 接口的实现类,如果是返回 true,否则返回 false

ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List);//true

List list = new ArrayList();
System.out.println(list instanceof ArrayList);//true

5、obj 为 class 类的直接或间接子类

public class Person {
 
}
public class Man extends Person{
     
}

测试:

Person p1 = new Person();
Person p2 = new Man();
Man m1 = new Man();
System.out.println(p1 instanceof Man);//false
System.out.println(p2 instanceof Man);//true
System.out.println(m1 instanceof Man);//true

转载于:https://www.cnblogs.com/ysocean/p/8486500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值