1. 概念
instanceof 是一种类型比较运算符(Type Comparision Operator),compares an object to a specified type,You can use it to test if an object isan instance of a class,an instance of a subclass, or an instance of a class that implements a particular interface.
即格式为:object instanceof Class, 注意分清 childCassObject instanceof parentClass 和 parentClassObjectinstanceof ChildClass
2. 例子
// 4个测试类
class Shape {}
class Circle extends Shape {}
class Square extends Shape {}
class Nothing {}
public class MainClass {
public static void main(String[] args){
Shape shape = new Circle(); //Upcasting, it's ok
Circle circle = (Circle)shape; //Downcasting, compile OK, run OK
Square square = (Square)shape; //Downcasting, compile OK, but it will throw ClassCastException in runtime, because shape is instantiated as Circle
//鉴于上面的问题,我们需要在进行downcasting时,需要先判断shape是否被实例化为Square。
if (shape instanceof Square) { // false
Square square1 = (Square) shape; // It’s OK
} else if (shape instanceof Circle) { // true
Circle circle1 = (Circle) shape; // It’s OK
} else if (shape instanceof Nothing) { // Compile error, because there is no relationship between Shape and Nothing
} else if (shape instanceof Shape) { // It’s also OK
}
//从上面可以看出,instanceof可以帮助我们来判断其两边的对象是否有”关联”关系
//如果没有,则编译不过,例如shape instanceof Nothing或circle instanceof Square
//如果有,也要注意upcasting时,基类用的哪个子类实例化.
//请注意下面的情况,区分“初始化”与“实例化”
Shape test = null; //initialized to null
boolean result = test instanceof Shape; //result is false, because test is just initialized(初始化) to null, but not instantiated(实例化).
//如果这样,是OK
Shape test1 = new Shape();
boolean result1 = test1 instanceof Shape; //result1 is true, because test1 is instantiated.
boolean result2 = test1 instanceof Circle; //result2 is false, because test1 is just instantiated as Shape.
}
}
3. 总结:
1) 为了在downcasting时不出错,最好用instanceof 来判断下对象的类型
2) Instanceof 的定义是”test if an object is of a specified type”, 即判断某个对象是否属于某种特定类型,也就是是否有某种关联。
3) 既可以用 childClassObject instanceof parentClass, 也可以 parentClassObject instanceof childClass, 但后者不一定都是false,要根据parentClassObject实例化为的子类对象类型来确定
4) 注意 null
is not an instance of anything
5) instanceof
can only be used with reference types, not primitive types. 即只能用在引用类型,对于基本类型(int, long)不能用,这跟另外一个Class.isAssignableFrom(...)是有区别的,后者可以支持基本类型。对于这两个的详细区别,后面的文章会介绍。