当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Class isAssignableFrom()用法及代码示例


java.lang.Class类的isAssignableFrom()方法用于检查指定类的对象是否兼容以分配给该Class的实例。如果两个类都相同,或者指定的类是超类或超接口,则它将兼容。如果指定类的对象可以强制转换为该类的实例,则该方法返回true。否则返回false。

用法:

public boolean isAssignableFrom(Class<T> class)

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


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

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

示例1:

// Java program to demonstrate isAssignableFrom() 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 isAssignableFrom() method 
        System.out.println("Is c compatible: "
                           + myClass.isAssignableFrom(c)); 
    } 
}

输出:

Class represented by myClass: class Test
Class represented by c: class java.lang.String
Is c compatible: false

示例2:

// Java program to demonstrate isAssignableFrom() 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 isAssignableFrom() method 
        System.out.println("Is c compatible: "
                           + myClass.isAssignableFrom(c)); 
    } 
}

输出:

Class represented by myClass: class Test
Class represented by c: class Test
Is c compatible: true

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



相关用法


注:本文由纯净天空筛选整理自srinam大神的英文原创作品 Class isAssignableFrom() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。