instanceof 严格来说是 Java 中的一个双目运算符,用来测试一个对象是否为一个类的实例,具体用法为:

boolean result = object instanceof Class

其中 object 为一个对象,Class 表示一个类或者一个接口,当 object Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果 result 都返回 true,否则返回 false

Tips:编译器会检查 object 是否能转换成右边的 Class 类型,如果不能转换则直接报错,如果不能确定其类型,则编译通过,具体类型则看运行时确定。

以下讲一下注意事项:

1、object 不能是基本类型,必须为引用类型

int i = 1;
System.out.println(i instanceof Object); //编译不通过 会报错(Inconvertible types; cannot cast 'int' to 'java.lang.Object')
System.out.println(i instanceof Integer); //编译不通过 会报错(Inconvertible types; cannot cast 'int' to 'java.lang.Integer')

instanceof 运算符只能用作对象的判断。

【Java用法】Java关键字 —— instanceof_System

2、object 为 Class 类的实例对象

Double d = new Double(1);
System.out.println(d instanceof Double); // true

这是最普遍的一种用法。

3、object 为 null

JavaSE 规范 中对 instanceof 运算符的规定就是:如果 object 为 null,那么将返回 false。

4、object 为 Class 接口的实现类

例如我们常用的 ArrayList 就是 List 的实现类,HashMap Map 的实现类,所以我们用 instanceof 运算符判断 某个对象是否是 List / Map 接口的实现类,如果是返回 true,否则返回 false

ArrayList<String> arrayList = new ArrayList<>();
System.out.println(arrayList instanceof List); // true
HashMap<String, Object> hashMap = new HashMap<>(16);
System.out.println(hashMap instanceof Map); // true

System.out.println(StrUtil.center("分隔线", 10, "-"));

List<String> stringList = new ArrayList<>();
System.out.println(stringList instanceof ArrayList); // true
Map<String, Object> stringObjectMap = new HashMap<>(16);
System.out.println(stringObjectMap instanceof HashMap); // true

输出结果:

【Java用法】Java关键字 —— instanceof_System_02

5、object 为 Class 类的继承类(包括直接或间接继承)

public class Animal {
}

class Dog extends Animal {

}

class Test {

    public static void main(String[] args) {
        Animal animal1 = new Animal();
        Animal animal2 = new Dog();
        Dog dog = new Dog();
        System.out.println(animal1 instanceof Dog); // false
        System.out.println(animal1 instanceof Animal); // true
        System.out.println(animal2 instanceof Dog); // true
        System.out.println(dog instanceof Animal); // true
        System.out.println(dog instanceof Dog); // true
    }
}

注意第一种情况, animal1 instanceof DogDog Animal 的子类,而 Animal 不是 Dog 的子类,所以返回结果为 false

 

完结!