類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