当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Class 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-



相关用法


注:本文由纯净天空筛选整理自srinam大神的英文原创作品 Class cast() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。