The usage of instanceof keyword in Java

concept

instanceof is a binary operator in Java, similar to ==, >, < and other operators.

instanceof is a Java reserved keyword. what it does isTests whether the object on its left is an instance of the class on its right, returning boolean data type

The following example creates the displayObjectClass() method to demonstrate the Java instanceof keyword usage:

Code case

package cn.test;

import java.util.ArrayList;
import java.util.Vector;

public class TestMain {
    
    
    public static void main(String[] args) {
    
    
        Object testObject = new ArrayList();
        displayObjectClass(testObject);
        displayString("字");

    }
    public static void displayObjectClass(Object o) {
    
    
        if (o instanceof Vector)
            System.out.println("对象是 java.util.Vector 类的实例");
        else if (o instanceof ArrayList)
            System.out.println("对象是 java.util.ArrayList 类的实例");
        else
            System.out.println("对象是 " + o.getClass() + " 类的实例");
    }

    public static void displayString(String str){
    
    
        if (str instanceof String)
            System.out.println("是String类的实例");
    }
}

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45525272/article/details/123469020