1. instanceof 是一个操作符
if(a instanceof B){
}
表示:a 是不是 B 这种类型
2. isInstance是Class类的一个方法
if(B.Class.isInstance(a)){
};
表示:a 是否能强转为 B 类型
3. 代码
interface CFather {
}
class DFather {
}
class C implements CFather {
}
class D extends DFather {
}
public class WangboTest1 {
public static void main(String[] args) {
C c = new C();
D d = new D();
// obj instanceof class:这个对象是不是这种类型.
// 测试1:一个对象是本身类的一个对象
// true
System.out.print("c instanceof C: ");
System.out.println(c instanceof C);
// true
System.out.print("d instanceof D: ");
System.out.println(d instanceof D);
// 测试2:一个对象是本身类父类(父类的父类)和接口的一个对象
// true
System.out.print("c instanceof CFather: ");
System.out.println(c instanceof CFather);
// true
System.out.print("d instanceof DFather: ");
System.out.println(d instanceof DFather);
// 测试3:所有对象都是object
// true
System.out.print("c instanceof Object: ");
System.out.println(c instanceof Object);
// true
System.out.print("d instanceof Object: ");
System.out.println(d instanceof Object);
// 测试4:凡是null相关的都是false
// false
System.out.print("null instanceof Object: ");
System.out.println(null instanceof Object);
// false
System.out.print("null instanceof CFather: ");
System.out.println(null instanceof CFather);
// false
System.out.print("null instanceof DFather: ");
System.out.println(null instanceof DFather);
// class.isInstance(obj):这个对象能不能被转化为这个类
// 测试1:一个对象是本身类的一个实例
// true
System.out.print("C.class.isInstance(c): ");
System.out.println(C.class.isInstance(c));
// true
System.out.print("D.class.isInstance(d): ");
System.out.println(D.class.isInstance(d));
// 测试2:一个对象能被转化为本身类所继承的类(父类的父类)和实现的接口(接口的父接口)强转
// true
System.out.print("CFather.class.isInstance(c): ");
System.out.println(CFather.class.isInstance(c));
// true
System.out.print("DFather.class.isInstance(d): ");
System.out.println(DFather.class.isInstance(d));
// 测试3:所有对象都能被Object强转
// true
System.out.print("Object.class.isInstance(c): ");
System.out.println(Object.class.isInstance(c));
// true
System.out.print("Object.class.isInstance(d): ");
System.out.println(Object.class.isInstance(d));
// 测试4:凡是和null相关的都是false
// false
System.out.print("Object.class.isInstance(null): ");
System.out.println(Object.class.isInstance(null));
// false
System.out.print("D.class.isInstance(null): ");
System.out.println(D.class.isInstance(null));
// false
System.out.print("C.class.isInstance(null): ");
System.out.println(C.class.isInstance(null));
}
}
结果
c instanceof C: true
d instanceof D: true
c instanceof CFather: true
d instanceof DFather: true
c instanceof Object: true
d instanceof Object: true
null instanceof Object: false
null instanceof CFather: false
null instanceof DFather: false
C.class.isInstance(c): true
D.class.isInstance(d): true
CFather.class.isInstance(c): true
DFather.class.isInstance(d): true
Object.class.isInstance(c): true
Object.class.isInstance(d): true
Object.class.isInstance(null): false
D.class.isInstance(null): false
C.class.isInstance(null): false