Java中的类 isAssignableFrom() 方法及示例
Java.lang.Class 类的isAssignableFrom()方法用于检查指定类的对象是否兼容分配给该类的实例。如果两个类相同,或者指定的类是超类或超接口,它将兼容。如果指定类的对象可以转换为此类的实例,则该方法返回 true。否则返回 false。
句法:
public boolean isAssignableFrom(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-