isAssignableFrom 和 instanceof

一、isAssignableFrom

方法定义:   boolean isAssignableFrom(Class<?> cls)  

     判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口。

注意:isAssignableFrom 只能用于类与类或接口与接口之间的比较,不能用于类与接口之间的比较

/*
 * 定义如下 
 * FatherInterface:接口 
 * ChildInterface:接口,继承于FatherInterface
 * Father:普通java类
 * Child:普通java类,继承于Father,并实现了ChildInterface
 */
boolean assignableFrom = false;

// FatherInterface与FatherInterface相同,所以为true
assignableFrom = FatherInterface.class.isAssignableFrom(FatherInterface.class);

// FatherInterface是ChildInterface相同,所以为true
assignableFrom = FatherInterface.class.isAssignableFrom(ChildInterface.class);

// Father是Child的父类,所以为true
assignableFrom = Father.class.isAssignableFrom(Child.class);

// Father与Father相同,所以为true
assignableFrom = Father.class.isAssignableFrom(Father.class);

//Child虽然实现了ChildInterface,isAssignableFrom比较的是两个类或两个接口之间的关系
//不能比较类与接口之间的关系,所以为false
assignableFrom=Child.class.isAssignableFrom(ChildInterface.class);


二、instanceof

Java  中的instanceof 运算符是用来在运行时指出对象是否是特定类或特定接口的一个实例。

/*
 * 定义如下 
 * FatherInterface:接口 
 * ChildInterface:接口,继承于FatherInterface
 * Father:普通java类
 * Child:普通java类,继承于Father,并实现了ChildInterface
 */
Child child = new Child();
boolean flag = false;
//flag=true  Child自己的实例
flag = child instanceof Child; 

//flag=true  Child继承于Father
flag = child instanceof Father; 

//flag=true Child实现了ChildInterface
flag = child instanceof ChildInterface; 

//flag=true Child实现了ChildInterface,ChildInterface继承于FatherInterface
flag = child instanceof FatherInterface;

在开发中,对象强转前,我们最好用instanceof判断下,避免类型转换异常

if(child instanceof ChildInterface){
	ChildInterface childInterface=(ChildInterface) child;
}















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值