instanceof
是 Java 的保留关键字,它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
代码中可能遇到的情况:
1、基本数据类型
如上图,这种情况会报错。将右边的类型改为引用类型:
依旧报错,改成特殊的null
:
依旧报错,由此得出:基本类型不能用于 instanceof 判断。
为了验证这一点,换一个基本数据类型double
进行测试:
依旧报错,可以验证结论正确。
2、引用类型
创建如下关系的类和接口:
测试一:
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = new Animal();
Animal cat = new Cat();
System.out.println("dog instanceof Dog的结果是:" + (dog instanceof Dog)); // true
System.out.println("dog instanceof Big的结果是:" + (dog instanceof Big)); // true
System.out.println("animal instanceof Big的结果是:" + (animal instanceof Big)); // true
System.out.println("animal instanceof Dog的结果是:" + (animal instanceof Dog)); // false
System.out.println("cat instanceof Animal的结果是:" + (cat instanceof Animal)); // true
System.out.println("cat instanceof Cat的结果是:" + (cat instanceof Cat)); // true
}
打印结果:
dog instanceof Dog的结果是:true
dog instanceof Big的结果是:true
animal instanceof Big的结果是:true
animal instanceof Dog的结果是:false
cat instanceof Animal的结果是:true
cat instanceof Cat的结果是:true
测试二:
基本类型
完全不能用于
instanceof 判断null
只能放在instanceof
关键字的左边
3、数组类型
延续引用类型示例,可以得到数组类型用来判断时的情况:
Dog[] dog = new Dog[3];
Animal animal = new Animal();
System.out.println("dog instanceof Dog[]的打印结果是:"+(dog instanceof Dog[]));
System.out.println("dog instanceof Big[]的打印结果是:"+(dog instanceof Big[]));
打印结果:
dog instanceof Dog[]的打印结果是:true
dog instanceof Big[]的打印结果是:true
特别地,基本类型的数组也是可以用来判断的:
int[] arr = new int[3];
System.out.println("arr instanceof int[]的打印结果是:"+(arr instanceof int[]));
打印结果:
arr instanceof int[]的打印结果是:true
4、应用场景
instanceof
关键字一般用于强制转换
,在强转之前用它来判断是否可以强制转换:
/**
*========================================
* @方法说明 : 空判断 空返回true
* @param obj
* @return boolean
* @exception
*========================================
*/
public static boolean isEmpty(Object obj) {
if (obj == null || "null".equals(obj.toString()) || "".equals(obj.toString())) {
return true;
}
if (obj instanceof String) {
return ((String) obj).trim().length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
return false;
}