我是靠谱客的博主 搞怪眼神,最近开发中收集的这篇文章主要介绍Java中Class类中两个值得注意的进行类型动态转换的方法,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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来指定具体表示的是哪种类型。

最后

以上就是搞怪眼神为你收集整理的Java中Class类中两个值得注意的进行类型动态转换的方法的全部内容,希望文章能够帮你解决Java中Class类中两个值得注意的进行类型动态转换的方法所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部