考虑到进行强制类型转换时可能出现异常,因此进行类型转换之前应先通过instanceof运算符来判断是否可以成功转换。看下面这个例子:
public class TestConversion
{
public static void main(String[] args)
{
double d = 13.4;
long l = (long)d;
System.out.println(l);
int in = 5;
//下面代码编译时出错:试图把一个数值型变量转换为boolean型,
//编译时候会提示: 不可转换的类型
//boolean b = (boolean)in;
Object obj = "Hello";
//obj变量的编译类型为Object,是String类型的父类,可以强制类型转换
//而且obj变量实际上类型也是String类型,所以运行时也可通过
String objStr = (String)obj;
System.out.println(objStr);
//定义一个objPri变量,编译类型为Object,实际类型为Integer
Object objPri = new Integer(5);
//objPri变量的编译类型为Object,是String类型的父类,可以强制类型转换
//而objPri变量实际上类型是Integer类型,所以下面代码运行时引发ClassCastException异常
String str = (String)objPri;
}
}
例如,上面的String str = (String)objPri;代码运行时会引发ClassCastException异常,这是因为objPri不可转换为String类型。为了让代码更加健壮,可以将代码改为如下:
if(objPri instanceof String ){
String str = (String) objPri;
}
在进行强制类型转换之前,先用instatnceof运算符判断是否可以成功转换,从而避免出现ClassCastException异常。
instanceof运算符的前一个操作数通常是一个引用类型变量,后一个操作数通常是一个类(也可以是接口,可以把接口当作一种特殊的类),它用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是,则返回true,否则,返回false。
在使用instanceof运算符时需要注意:运算符前面操作数的编译时类型要么与后面的类相同,要么和后面的类具有父子继承关系,否则会引起编译错误。下面程序示范了instanceof运算符的用法:
public class TestInstanceof
{
public static void main(String[] args)
{
//声明hello时使用Object类,则hello的编译类型是Object,Object是所有类的父类
//但hello变量的实际类型是String
Object hello = "Hello";
//String是Object类的子类,所以返回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 a = "Hello";
//String类既不是Math类,也不是Math类的父类,所以下面代码编译无法通过
//System.out.println("字符串是否是Math类的实例:" + (a instanceof Math));
}
}
输出结果:
字符串是否是Object类的实例:true
字符串是否是String类的实例:true
字符串是否是Math类的实例:false
字符串是否是Comparable接口的实例:true
上面程序定义了一个hello变量,这个变量的编译时类型是Object类,但实际类型是String类。因为Object类是所有类、接口的父类,因此可以执行hello instanceof String和hello instanceof Math等。
但如果使用String hello = “Hello”来定义hello,则不能执行hello instanceof Math,因为hello的编译时类型是String,它并不是Math类,也不是Math类的父类。
instanceof运算符的作用是:在进行强制类型转换之前,首先判断前一个对象是否是后一个类的实例,是否可以成功转换,从而保证程序的安全性。