Java中Class类中两个值得注意的进行类型动态转换的方法

1 篇文章 0 订阅
1 篇文章 0 订阅

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


第一个方法asSubclass()

 

public <U> Class<? extends U> asSubclass(Class<U> clazz)

Casts this Class object to represent a subclass of the class represented by the specified class object. Checks that that the cast is valid, and throws a ClassCastException if 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 a Class object to pass it to an API that restricts the Class objects 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:

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

Throws:

ClassCastException - if this Class object 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> child = c.asSubClass(Father.class);  // “Child” extends “Father”


第二个方法cast()


public T cast(Object obj)

Casts an object to the class or interface represented by this Class object.

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<String> c = String.class;

Object o = “hello world!”;

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值