Java Class isInstance()方法及示例

Java Class isInstance()方法及示例

java.lang.Class类的isInstance()方法用于检查指定的对象是否可以被分配到这个类的实例中。如果指定的对象不是空的,并且可以被赋值到这个类的实例中,该方法返回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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程