java.lang.Class類的cast()方法用於將指定的對象強製轉換為此類的對象。該方法以對象形式轉換後返回對象。
用法:
public T[] cast(Object obj)
參數:此方法接受參數obj,它是要轉換的對象
返回值:此方法以對象形式轉換後返回指定的對象。
異常:該方法拋出:
- ClassCastException:如果對象不為null,並且不能分配給T類型。
下麵的程序演示了cast()方法。
範例1:
// Java program to demonstrate
// cast() method
import java.util.*;
public class Test {
public static Object obj;
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());
// Cast the object obj to object of myClass
// using cast() method
System.out.println("Object " + obj + " after cast "
+ "upon to class Test:"
+ myClass.cast(obj));
}
}
輸出:
Class represented by myClass:class Test Object null after cast upon to class Test:null
範例2:
// Java program to demonstrate
// cast() method
import java.util.*;
class Main {
private static int obj = 10;
public static void main(String[] args)
throws ClassNotFoundException
{
try {
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass:"
+ myClass.toString());
// Cast the object obj to object of myClass
// using cast() method
System.out.println("Object " + obj + " after cast "
+ "upon to class Test:"
+ myClass.cast(obj));
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
Class represented by myClass:class Main java.lang.ClassCastException:Cannot cast java.lang.Integer to Main
參考: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#cast-java.lang.Object-
相關用法
- Java Class getAnnotatedInterfaces()用法及代碼示例
- Java Class getCanonicalName()用法及代碼示例
- Java Class getClasses()用法及代碼示例
- Java Class getDeclaredAnnotationsByType()用法及代碼示例
- Java Class getDeclaredAnnotations()用法及代碼示例
- Java Class getAnnotations()用法及代碼示例
- Java Class getConstructors()用法及代碼示例
- Java Class getDeclaredClasses()用法及代碼示例
- Java Class getDeclaredConstructors()用法及代碼示例
- Java Class getMethods()用法及代碼示例
- Java Class getSimpleName()用法及代碼示例
- Java Class getFields()用法及代碼示例
- Java Class getDeclaredMethods()用法及代碼示例
- Java Class getDeclaredFields()用法及代碼示例
- Java Class getTypeName()用法及代碼示例
注:本文由純淨天空篩選整理自srinam大神的英文原創作品 Class cast() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。