Java Class isAssignableFrom()方法及示例
java.lang.Class类的isAssignableFrom()方法用于检查指定类的对象是否可以分配给该类的实例。如果两个类都是相同的,或者指定的类是超类或超接口,那么它将是兼容的。如果指定的类的对象可以被赋值到这个类的实例中,该方法返回true。否则会返回false。
语法。
public boolean isAssignableFrom(Class<T> 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-