📜  Java中的类 isInstance() 方法及示例

📅  最后修改于: 2022-05-13 01:55:30.940000             🧑  作者: Mango

Java中的类 isInstance() 方法及示例

Java.lang.Class 类isInstance()方法用于检查指定对象是否兼容分配给该类的实例。如果指定对象为非 null 并且可以强制转换为此类的实例,则该方法返回 true。否则返回 false。

句法:

public boolean isInstance(Object object)

参数:此方法接受对象作为参数,该参数是要检查与此类实例的兼容性的指定对象。

返回值:如果指定的对象非空,则该方法返回true ,并且可以强制转换为该类的实例。否则返回false

下面的程序演示了 isInstance() 方法。

示例 1:

// Java program to demonstrate isInstance() method
  
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
  
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
  
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
  
        // get the Class instance using forName() method
        Class c = Class.forName("java.lang.String");
  
        System.out.println("Class represented by c: "
                           + c.toString());
  
        // Check if object c is compatible
        // using isInstance() method
        System.out.println("Is c compatible: "
                           + myClass.isInstance(c));
    }
}
输出:
Class represented by myClass: class Test
Class represented by c: class java.lang.String
Is c compatible: false

示例 2:

// Java program to demonstrate isInstance() method
  
public class Test {
    public static void main(String[] args)
        throws ClassNotFoundException
    {
  
        // returns the Class object for this class
        Class myClass = Class.forName("Test");
  
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
  
        // get the Class instance using forName() method
        Class c = Class.forName("Test");
  
        System.out.println("Class represented by c: "
                           + c.toString());
  
        // Check if object c is compatible
        // using isInstance() method
        System.out.println("Is c compatible: "
                           + myClass.isInstance(c));
    }
}
输出:
Class represented by myClass: class Test
Class represented by c: class Test
Is c compatible: false

参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#isInstance-java.lang.Object-