Java类class cast()方法及示例

本文详细介绍了Java中Class类的cast()方法,解释了如何使用此方法进行对象的类型转换,包括其语法、参数、返回值及可能抛出的异常,并通过一个实例展示了其具体用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类class cast()方法 (Class class cast() method)

  • cast() method is available in java.lang package.

    在java.lang包中提供了cast()方法

  • cast() method casts this Object to the class or an interface denoted by this Class object.

    cast()方法将此Object强制转换为该Class或此Class对象表示的接口。

  • cast() 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.

    cast()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名访问该方法,则会收到错误消息。

  • cast() method may throw ClassCastException at the time of casting an Object.

    cast()方法可能会在投射对象时抛出ClassCastException

    ClassCastException: In this exception when the given object is not null.

    ClassCastException :在此异常中,给定对象不为null。

Syntax:

句法:

    public Type cast(Object o);

Parameter(s):

参数:

  • Object o – represents the object to be cast.

    对象o –表示要投射的对象。

Return value:

返回值:

The return type of this method is Type, it returns the following values based on the given cases,

此方法的返回类型为Type ,它根据给定的情况返回以下值:

  • It returns the casting object.

    它返回转换对象。

  • It returns null when the given Object is null.

    当给定的Object为null时,它返回null。

Example:

例:

// Java program to demonstrate the example 
// of Type cast(Object o) method of Class 

class A1 {
 // A1 Blank implementation
}

class B1 extends A1 {
 // B1 Blank implementation
}

public class MainClass {
 public static void main(String[] args) {
  // Creting an instance of MainClass
  MainClass mc = new MainClass();

  // Display Class
  System.out.println("mc.getClass():" + mc.getClass());

  // Creating an instance of class A1 and B1
  A1 a = new A1();
  B1 b = new B1();

  // Casting object b to a by using cast(b) method
  Object a1 = A1.class.cast(b);

  // Display Class of object a , b and a1
  System.out.println("a.getClass(): " + a.getClass());
  System.out.println("b.getClass(): " + b.getClass());
  System.out.println("a1.getClass(): " + a1.getClass());
 }
}

Output

输出量

mc.getClass():class MainClass
a.getClass(): class A1
b.getClass(): class B1
a1.getClass(): class B1


翻译自: https://www.includehelp.com/java/class-class-cast-method-with-example.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值