一、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;
}