通过分析可以发现向下转型本身是一件存在有安全隐患的操作,所以为了保证向下转型的正确性,往往需要在进行转型之前进行判断,判断某个实例是否是某个类的对象,这个就需要通过instanceof语法来实现,语法如下:
对象 instanceof 类
该判断将返回一个boolean类型,如果是true表示实例是指定类对象。
范例:观察instanceof的使用
public class JavaDemo {
public static void main(String args[]) {
Person per = new Person() ; // 不转型
System.out.println(per instanceof Person); // true
System.out.println(per instanceof SuperMan); // false
}
}
范例:观察instanceof关键字
public class JavaDemo {
public static void main(String args[]) {
Person per = new SuperMan() ; // 向上转型
System.out.println(per instanceof Person); // true
System.out.println(per instanceof SuperMan); // true
}
}
所以在日后进行项目的开发过程之中,如果要执行对象的向下转型,最好先判断一次。
public class JavaDemo {
public static void main(String args[]) {
Person per = new SuperMan() ; // 向上转型
if (per instanceof SuperMan) {
SuperMan man = (SuperMan) per ;
System.out.println(man.fly());
System.out.println(man.fire());
}
}
}
在以后进行一些完善性的程序开发的过程之中,对于转型之前一定要使用instanceof判断。