instanceof 的作用
在进行强制类型转换之前, 首先判断这个对象是否是这个要转换的类的实例, 确保是否可以强制转换
Object hello = "Hello";
System.out.println(hello instanceof Object);
System.out.println(hello instanceof String);
System.out.println(hello instanceof Comparable);
System.out.println(hello instanceof Math);
// result
true
true
true
false
// String a = "Hello";
// System.out.println(a instanceof Math);
Object是所有类或接口的父类,所以上面的都可以成功转换
但 String 不是 Math类型, 也不是Math类型的父类, 所以无法转换
Object objPri = new Integer(5);
if (objPri instanceof String)
{
String str = (String)objPri;
System.out.println(str);
}
System.out.println(objPri);