类class isAssignableFrom()方法 (Class class isAssignableFrom() method)
isAssignableFrom() method is available in java.lang package.
isAssignableFrom()方法在java.lang包中可用。
isAssignableFrom() method is used to check whether the class or an interface denoted by this Class object is either the same as, or the Class object is a superclass or superinterface.
isAssignableFrom()方法用于检查此Class对象所表示的类或接口是否与该类或接口相同,或者该Class对象是超类还是超接口。
isAssignableFrom() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
isAssignableFrom()方法是一个非静态方法,只能使用类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
isAssignableFrom() method may throw an exception at the time of assigning an object.
在分配对象时, isAssignableFrom()方法可能会引发异常。
NullPointerException: In the exception, when the given class exists null.
NullPointerException :在异常中,当给定的类存在时为null。
Syntax:
句法:
public boolean isAssignableFrom(Class class);
Parameter(s):
参数:
Class class – represents the Class object to be determined.
类class –表示要确定的Class对象。
Return value:
返回值:
The return type of this method is boolean, it returns a boolean value based on the following cases,
此方法的返回类型为boolean ,它基于以下情况返回布尔值:
It returns true, when the object of class is assignable to object of this Class.
当类的对象可分配给该类的对象时,它返回true 。
It returns false, when the object of class is not assignable to object of this Class.
当class的对象不可分配给该Class的对象时,它返回false 。
Example:
例:
// Java program to demonstrate the example
// of boolean isAssignableFrom(Class class) method of Class
public class Parent {
public static void main(String[] args) throws Exception {
// Create and Return Parent Class object
Parent p = new Parent();
Class cl1 = p.getClass();
// Create and Return Child Class object
Child ch = new Child();
Class cl2 = ch.getClass();
// We are checking the given Parent class is
// Assignable from Child Class
boolean child = cl2.isAssignableFrom(cl1);
System.out.println("Is" + " " + cl1.getSimpleName() + " " + "Assignable from Child: " + " " + child);
// We are checking the given Child class is
// Assignable from Parent Class
boolean parent = cl1.isAssignableFrom(cl2);
System.out.println("Is" + " " + cl2.getSimpleName() + " " + "Assignable from Parent: " + " " + parent);
}
}
class Child extends Parent {
public Child() {
// Default Constructor with blank implementation
}
}
Output
输出量
Is Parent Assignable from Child: false
Is Child Assignable from Parent: true
翻译自: https://www.includehelp.com/java/class-class-isassignablefrom-method-with-example.aspx