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 允许你选择任何用户自定义日期时间 ...
随机推荐
- HDU——1009FatMouse' Trade(贪心+结构体+排序)
FatMouse' Trade Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- [HDNOIP2017提高组]题解
(送给外省的同学们:HD = 海淀) [HDNOIP201701]小鱼干 试题描述 小喵喵有 n 个小鱼干排成一列,其中第 i 个小鱼干有两种属性,美味度 ai 和特殊度 bi. 现在小喵喵要吃掉一些 ...
- 马士兵hadoop第五课:java开发Map/Reduce(转)
马士兵hadoop第一课:虚拟机搭建和安装hadoop及启动 马士兵hadoop第二课:hdfs集群集中管理和hadoop文件操作 马士兵hadoop第三课:java开发hdfs 马士兵hadoop第 ...
- word文档的导出(用freemarker模板导出)(桃)
1.将要导出的word文档另存为xml格式的 2.用文档编辑器打开(如:notepad++),将要展示的数据用${name}的形式替换,“name”对应数据库中的字段 3.根据模板生成 package ...
- vue slot 插槽备忘
老是记不住插槽咋回事 记录下来备忘 父组件 <tab><template slot="boy" slot-scope="test">{{ ...
- Linux 虚拟地址与物理地址的映射关系分析【转】
转自:http://blog.csdn.net/ordeder/article/details/41630945 版权声明:本文为博主(http://blog.csdn.net/ordeder)原创文 ...
- linux 调试常用命令
top 参数 1 ,查看多核cpu 也可用 mpstat -P ALL pstate PID 查看进程堆栈 pmap -x PID 查看进程 内存段 ldd XXX.so 查看 .so 的link ...
- hdu 2462(欧拉定理+高精度快速幂模)
The Luckiest number Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Othe ...
- LeetCode OJ——Longest Valid Parentheses
http://oj.leetcode.com/problems/longest-valid-parentheses/ 最大括号匹配长度,括号是可以嵌套的 #include <string> ...
- 天梯赛 - L2-002 链表去重
GG思密达,第二个测试点的三分怎么也拿不上,我还是比较熟悉指针,用指针来写~,写完去上概率论 题目链接:https://www.patest.cn/contests/gplt/L2-002 #incl ...