java程序中出现两个class,Java中Class类中两个值得注意的进行类型动态转换的方法...

Java中的Class类有两个重要的方法:cast()和asSubclass()。这两个方法都是用于Class类进行运行时(run-time)阶段的类型转换的。下面来看看他们的定义和使用:

第一个方法asSubclass()

public Class extends U> asSubclass(Class clazz)

Casts thisClassobject to represent a subclass of the class represented by the specified class object. Checks that that the cast is valid, and throws aClassCastExceptionif it is not. If this method succeeds, it always returns a reference to this class object.

This method is useful when a client needs to "narrow" the type of aClassobject to pass it to an API that restricts theClassobjects that it is willing to accept. A cast would generate a compile-time warning, as the correctness of the cast could not be checked at runtime (because generic types are implemented by erasure).

Returns:

thisClassobject, cast to represent a subclass of the specified class object.

Throws:

ClassCastException- if thisClassobject does not represent a subclass of the specified class (here "subclass" includes the class itself).

Since:

1.5

使用实例:

Class> c = Class.forName(“MyClass”);

Class child = c.asSubClass(Father.class);  // “Child” extends “Father”

第二个方法cast()

publicTcast(Objectobj)

Casts an object to the class or interface represented by thisClassobject.

Parameters:

obj- the object to be cast

Returns:

the object after casting, or null if obj is null

Throws:

ClassCastException- if the object is not null and is not assignable to the type T.

Since:

1.5

使用实例:

这个函数可以简单的理解为将一个Object类型的对象转换成Class表示的类型的对象(其实在java中Class类就是所有类型字节码的一种抽象,或者简单理解为在java中就是用于来说明类型的类型,因为java中一切都是类,所以“类”(类型)也是是类,而这个类就是Class)。

Class c = String.class;

Object o = “hello world!”;

String s = c.cast(o);      // 将Object类型转成这里的Class表示的类型,即String类型

Java中的Class类可以表示java中的所有类型,主要通过Class中的T来指定具体表示的是哪种类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值