Java instanceof Example: Check Object Type

In Java, we can use the instanceof keyword to determine whether an object is an instance of a certain class.

Here is an example code:

public class MyClass {
    public static void main(String[] args) {
        MyClass obj = new MyClass();

        if (obj instanceof MyClass) {
            System.out.println("obj是MyClass类的实例");
        } else {
            System.out.println("obj不是MyClass类的实例");
        }
    }
}

In the above code, we created an object of the MyClass class called obj. We then used the instanceof keyword to check if obj is an instance of the MyClass class. If it is, we output “obj is an instance of the MyClass class”; otherwise, we output “obj is not an instance of the MyClass class”.

bannerAds