📜  Java中的类 cast() 方法及示例

📅  最后修改于: 2022-05-13 01:55:09.114000             🧑  作者: Mango

Java中的类 cast() 方法及示例

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-