上周的学习中学习到了运行时类型信息
的两种形式:
1)传统的类型向下转换,运行时类型信息
确保类型转换的正确性,如果执行了错误的类型转换,即抛出ClassCastException类型转换异常;
2)表示对象类型的Class对象,通过查询Class对象可以获取运行时所需的一些信息。
而第三种形式则是本文提到的关键字instanceof
一.类型转换前先进行类型判断
java类进行向下强制类型转型时需要先进行类型判断:编译器无法在编译器获取子类或实现类的具体类型,如果在不确定对象类型的情况下进行强制转换,即会得到一个类型转换异常,使用instanceof即可在运行时对对象的类型进行判断。
- 静态instanceof的用法
class Shape{}
class Circle extends Shape{}
Shape shape = new Circle();
if (shape instanceof Circle){
...
}
使用静态instanceof,每当添加一个子类时,都需要对累心判断的方法进行修改。如添加一个新的子类继承Shape
class Square extends Shape{}
则需要将类型判断方法修改为:
Shape shape = new Circle();
if (shape instanceof Circle){
...
}else if (shape instanceof Square ){
...
}
-
动态instanceof的用法
动态instanceof指的是使用Class.isInstance方法动态测试对象的类型,通过对isInstance方法的使用,就可以替代上述单调的instanceof逻辑判断,并且在添加新的子类时也无需对判断代码进行修改。
public void castType(Class<? extends Shape> shape,Shape realShape){
if (shape.isInstance(realShape)){
...
}
}
Shape shape = new Circle;
castType(Circle.class ,shape );
castType(Square.class ,shape );
二.instanceof与Class的等价性
1.使用instanceof与isInstance判断类相等的方式得到的结果是一致的;
2.使用==和equals判断类相等的方式得到的结果也是一致的;
3.而instanceof方式,不仅考虑了自身类,也考虑了继承,即“”“你是这个类或这个类的派生类吗?”,而使用==判断方式,则只考虑当前比较的确切类