Java 中如何判断能否向上转型
来源:互联网 发布:mac怎么用键盘代替鼠标 编辑:程序博客网 时间:2024/06/06 07:15
由于JAVA具体多态的特性,因此在我们编写代码的时候经常会用到将某一个类的对象cast成另外一个类的对象。当我都知道这两个的类的继承关系的,这种操作应该是安全的,但是有时候类的继承关系太复杂时,可能我们直接去cast就会有问题。
那么JAVA有没有提供一种机制让程序员检查能否将一个对象转换另外一个对象呢? 答案是有的。如下:
isAssignableFrom Determines if the class or interface represented by this
那么JAVA有没有提供一种机制让程序员检查能否将一个对象转换另外一个对象呢? 答案是有的。如下:
isAssignableFrom Determines if the class or interface represented by this
Class
object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class
parameter. It returns true
if so; otherwise it returns false
. If this Class
object represents a primitive type, this method returns true
if the specified Class
parameter is exactly this Class
object; otherwise it returns false
. Specifically, this method tests whether the type represented by the specified Class
parameter can be converted to the type represented by this Class
object via an identity conversion or via a widening reference conversion
Class classz = String.class;
File file;
if (clazz.isAssignableFrom(file.getClass())) {
return clazz.cast(file);
}
阅读全文
0 0
- Java 中如何判断能否向上转型
- Java中向上转型
- java中向上转型和向下转型
- java中向上转型和向下转型
- 【java】java中向上转型和向下转型相关知识
- Java中允许向上和向下转型
- java向上转型过程中方法重写
- java中向上转型(upcast)和向下转型(downcast)
- java中向上转型(upcast)和向下转型(downcast)
- java中向上转型(upcast)和向下转型(downcast)
- Java中向上转型和向下转型问题
- 【Java】向上转型 向下转型
- Java 向上转型,向下转型
- java 向上转型向下转型
- Java向上转型
- Java向上转型小议
- java向上转型
- java -多态--向上转型
- Setting Jar\'s Class Path
- Maven Plugin And LifeCycle
- Linux 查看端口的状态
- Python 实现交互式执行命令
- Enterprise DB(Postgres) connection
- Java 中如何判断能否向上转型
- traceroute article
- 如何在Java Unit Test中mock 静态方法
- DOM 常用到的功能模块
- POJ 3000 Frogger 笔记
- Git 常用的命令
- Maven Dependency Tree
- ElasticSearch 翻页查询
- [Leetcode 85] Maximal Rectangle