instanceof关键字是一个双目运算符,用来判断一个对象是否是该类的实例
boolean result = obj instanceof Class
1、obj必须为引用类型,不能为基本类型
int i = 0;
System.out.println(i.instanceof(Integer));//return false
System.out.println(i.instanceof(Object));//return false
2、obj为null则返回false
System.out.println(null.instanceof(Object));//return false
3、obj为class类的实例对象
Integer i = new Integer();
System.out.println(i.instanceof(Integer));//return true
4、obj为接口的实现类
ArrayList arrayList = new ArrayList();
System.out.println(arrayList.instanceof(List));//return true
List list = new ArrayList();
System.out.println(list.instanceof(ArrayList));//return true
5、obj为类的直接或间接子类
class Person{
}
class Man extends Person{
}
Person person1 = new Person();
Person person2 = new Man();
Man man = new Man();
System.out.println(person1.instanceof(Man));//return false
System.out.println(person2.instanceof(Man));//return true
System.out.println(man.instanceof(Man));//return true