|
用法:
(类型变量 instanceof 类|接口)
作用:
instanceof 操作符用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是则返回true 否则就返回false。
注意:
· instanceof前面的操作数的编译时类型要么与后面的类相同,要么与后面的类具有父子继承关系否则会引发编译错误。
一个简单的例子:
/** * instanceof 运算符 * @author Administrator * */
public class TestInstanceof { public static void main(String[] args) { //声明hello 时使用Object类,则hello的编译类型是Object //Object类是所有类的父类,但hello的实际类型是String Object hello = "Hello";
//String是Object的子类可以进行instanceof运算,返回true System.out.println("字符串是否为object类的实例:" + (hello instanceof Object));
//true System.out.println("字符串是否为String的实例:" + (hello instanceof String));
//false System.out.println("字符串是否为Math类的实例:" + (hello instanceof Math));
//String实现了Comparable接口,所以返回true System.out.println("字符串是否为Comparable类的实例:" +(hello instanceof Comparable));
/** * String 既不是Math类,也不是Math类的父类,故下面代码编译错误 */ //String a = "hello"; //System.out.println("字符串是否为Math类的实例:" // + (a instanceof Math));
} }
运行结果:
字符串是否为object类的实例:true 字符串是否为String的实例:true 字符串是否为Math类的实例:false 字符串是否为Comparable类的实例:true
通常在进行强制类型转换之前,先判断前一个对象是不是后一个对象的实例,是否可以成功转换,从而保证代码的健壮性。
|