Java中的class类的cast方法和asSubclass方法
一般来说cast是转型的意思,但是学java的时间也不短了,class类居然还有cast这个方法,这里来学习一下这个cast有何用。
第一次看到这个cast是在Spring的源码中,
spring-framework/spring-beans/src/main/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReader.java:517处有这样的一段代码:
/**
* Create the {@link BeanDefinitionDocumentReader} to use for actually
* reading bean definitions from an XML document.
* <p>The default implementation instantiates the specified "documentReaderClass".
* @see #setDocumentReaderClass
*/
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
}
当时我就好奇了,还有这个。
一、Java api
public T cast(Object obj);
Casts an object to the class or interface represented
解释的比较笼统,意思就是将一个对象装换为类或者接口。
二、代码示例
A.java
public class A {
public static void show() {
System.out.println("Class A show() function");
}
}
B.java
public class B extends A {
public static void show() {
System.out.println("Class B show() function");
}
}
TestCast.java
public class TestCast {
public static void main(String[] args) {
TestCast cls = new TestCast();
Class c = cls.getClass();
System.out.println(c);
Object obj = new A();
B b1 = new B();
b1.show();
// casts object
A a = new A();
System.out.println(a.getClass()); // 1. 打印a的class对象
a = A.class.cast(b1);
a.show();
System.out.println(obj.getClass());
System.out.println(b1.getClass());
System.out.println(a.getClass()); // 2. 打印a转换后的class对象
}
}
执行结果如下图:

这个例子是网上给出来的,核心为:a = A.class.cast(b1); 把a转化为了B类型,此处容易产生把b1转成A类型误解。
但是我很不满意啊,这个例子说明了啥??没看出来有卵用。
cast方法的源码
这个方法属于Class.java的
/**
* Casts an object to the class or interface represented
* by this {@code Class} object.
*
* @param obj the object to be cast
* @return 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
*/
@SuppressWarnings("unchecked")
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
有点晕,这个T是Class的泛型。这个方法只能转换当前类型或其子类下的对象。再来看一下这个isInstance方法
/**
* Determines if the specified {@code Object} is assignment-compatible
* with the object represented by this {@code Class}. This method is
* the dynamic equivalent of the Java language {@code instanceof}
* operator. The method returns {@code true} if the specified
* {@code Object} argument is non-null and can be cast to the
* reference type represented by this {@code Class} object without
* raising a {@code ClassCastException.} It returns {@code false}
* otherwise.
*
* <p> Specifically, if this {@code Class} object represents a
* declared class, this method returns {@code true} if the specified
* {@code Object} argument is an instance of the represented class (or
* of any of its subclasses); it returns {@code false} otherwise. If
* this {@code Class} object represents an array class, this method
* returns {@code true} if the specified {@code Object} argument
* can be converted to an object of the array class by an identity
* conversion or by a widening reference conversion; it returns
* {@code false} otherwise. If this {@code Class} object
* represents an interface, this method returns {@code true} if the
* class or any superclass of the specified {@code Object} argument
* implements this interface; it returns {@code false} otherwise. If
* this {@code Class} object represents a primitive type, this method
* returns {@code false}.
*
* @param obj the object to check
* @return true if {@code obj} is an instance of this class
*
* @since JDK1.1
*/
public native boolean isInstance(Object obj);
这个isInstance(Object obj)的意思是,obj这个对象是不是与这个Class对象兼容的类。

前面一句是,b1这个对象是不是a.getClass()的实例,后面一个是a是不是a.getClass()的实例。
我想了下,把上面cast所在的那句话反过来一下:

执行结果,报错了:

不能把A转成B,A是父类,B是子类,也就是cast括号中的是源对象,前面的getClass()是待转换成为的目标对象。
或者还有这种用法:

asSubclass方法
/**
* Casts this {@code Class} object to represent a subclass of the class
* represented by the specified class object. Checks that the cast
* is valid, and throws a {@code ClassCastException} if it is not. If
* this method succeeds, it always returns a reference to this class object.
*
* <p>This method is useful when a client needs to "narrow" the type of
* a {@code Class} object to pass it to an API that restricts the
* {@code 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).
*
* @param <U> the type to cast this class object to
* @param clazz the class of the type to cast this class object to
* @return this {@code Class} object, cast to represent a subclass of
* the specified class object.
* @throws ClassCastException if this {@code Class} object does not
* represent a subclass of the specified class (here "subclass" includes
* the class itself).
* @since 1.5
*/
@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) {
if (clazz.isAssignableFrom(this))
return (Class<? extends U>) this;
else
throw new ClassCastException(this.toString());
}
翻译一下方法上面的注释:将这个类强制转为另一个类的子类。当需要使类的类型窄化的时候,这个方法特别有用。
这是java.lang.Class中的一个方法,作用是将调用这个方法的class对象转换成由clazz参数所表示的class对象的某个子类。
上面的代码将strList.getClass()获取的class对象转换成Class<? extends List>,这么做似乎没有什么意义,因为我们很清楚strList.getClass()获取的class对象就是ArrayList,它当然是List.class的一个子类;但有些情况下,我们并不能确知一个class对象的类型,典型的情况是Class.forName()获取的class对象:Class.forName()的返回类型是Class<?>,但这显然太宽泛了,假设我们需要List.class类型的class对象,但我们传递给Class.forName的参数是未知的(可能是"java.lang.String",也可能是"java.util.ArrayList"),这时我们就可以用到asSubclass()这个方法了,如下:
asSubclass用于窄化未知的Class类型的范围,而instanceof用于判断一个对象引用是否是一个超类或者接口的子类/实现类,如果试图将instanceof用于Class类型的判断会引起编译错误。
通常在向某些参数严格限制的API传递参数时,为了避免产生编译警告,这个方法比较有用!
下次对asSubclass和cast这两个方法找一个好的例子,这里先了解一下。
Java中的class类的cast方法和asSubclass方法的更多相关文章
- StringBuffer类的delete()方法和deleteCharAt()方法的区别
引言 StringBuffer类的delete()方法和deleteCharAt()方法都是用来删除StringBuffer字符串中的字符 区别 1.对于delete(int start,int en ...
- 关于Object类的equals方法和hashCode方法
关于Object类的equals的特点,对于非空引用: 1.自反性:x.equals(x) return true : 2.对称性:x.equals(y)为true,那么y.equals(x)也为tr ...
- 并发基础篇(六):线程Thread类的start()方法和run()方法【转载】
[转载] 一.初识java的线程是通过java.lang.Thread类来实现的.VM启动时会有一个由主方法所定义的线程.可以通过创建Thread的实例来创建新的线程.每个线程都是通过某个特定Thre ...
- EF Core 中DbContext不会跟踪聚合方法和Join方法返回的结果,及FromSql方法使用讲解
EF Core中: 如果调用Queryable.Count等聚合方法,不会导致DbContext跟踪(track)任何实体. 此外调用Queryable.Join方法返回的匿名类型也不会被DbCont ...
- JAVA笔记7-Object类之toString方法和equals方法
位于rt.jar\java\lang\Object.class Object类是所有Java类的根基类(Java中只有一个根基类,C++中有多个).如果在类声明中未使用extends关键字指明其基类, ...
- Object类的toString方法和equals方法
Object类 概述 java.long.Object 类是java语言中的根类,即所有类的父类.它中描述的所有方法子类都可以使用.在对象实例化的时候,最终的父类就是Object 类Object是类层 ...
- Android中Path类的lineTo方法和quadTo方法画线的区别
转载:http://blog.csdn.net/stevenhu_223/article/details/9229337 当我们需要在屏幕上形成画线时,Path类的应用是必不可少的,而Path类的li ...
- Java基础知识强化84:System类之exit()方法和currentTimeMillis()方法
1. exit方法: public static void exit(int status): 终止当前正在运行的Java虚拟机.参数用作状态码:根据惯例,非0的状态码表示异常终止. 调用System ...
- SimpleDateFormat类介绍和 DateFormat类的format方法和parse方法
使用 SimpleDateFormat格式化日期 SimpleDateFormat 是一个以语言环境敏感的方式来格式化和分析日期的类.SimpleDateFormat 允许你选择任何用户自定义日期时间 ...
随机推荐
- [cogs729]圆桌问题(最大流)
传送门 模型 二分图多重匹配问题,可以用最大流解决. 实现 建立二分图,每个单位为X集合中的顶点,每个餐桌为Y集合中的顶点,增设附加源S和汇T. 1.从S向每个Xi顶点连接一条容量为该单位人数的有向边 ...
- 如何在Windows上卸载DB2
怎么在Windows下正确卸载DB2: http://www.360doc.com/content/11/1117/16/7485728_165237689.shtml ↑↑↑ 上面的文章挺复杂,我没 ...
- axis2生成webservice服务端返回String[]和String[][]一维数组和二维数组解析
环境:用axis2生成服务端,用aixs做客户端 1:直接返回String[]: public String[] testArr(String name) { String[] ret=new Str ...
- oracle中查询BLOB
1. 2.
- 【前端学习笔记】2015-09-01 附 split()方法、readyState
1.split():作用对象是一个字符串或者字符串对象,会要求设置两个参数(分割点(separator),分割出来的数量(number)),ps:1."2:3:4:5".split ...
- net5:Theme主题样式的动态变换,在内容页content中操作影响模板页的操作
原文发布时间为:2008-07-29 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Data;using System.Configuration ...
- 解决使用webbrowser请求url时数据传递丢失问题
问题: 使用“ this.webBrowser.Url = new Uri(webBrowserUrl);”方式请求Action(Java Web)并传递数据,在webBrowserUrl中携带的参数 ...
- es6总结(三)--数组
- jsp文件放在WebRoot下还是WebInfo下
观点一:(较为赞同) 安全性不是真正的原因,因为jsp是要解析后才显示到浏览器的,即使用户知道你jsp的路径,也不可能通过浏览器看到jsp源码的,而如果是通过其它手段入侵服务器的话,放在WEB-INF ...
- XMPP协议实现原理介绍(转)
XMPP协议简介 XMPP(Extensible Messageing and Presence Protocol:可扩展消息与存在协议)是目前主流的四种IM(IM:instant messagi ...