Java 中如何判断能否向上转型

来源:互联网 发布:mac怎么用键盘代替鼠标 编辑:程序博客网 时间:2024/06/06 07:15
由于JAVA具体多态的特性,因此在我们编写代码的时候经常会用到将某一个类的对象cast成另外一个类的对象。当我都知道这两个的类的继承关系的,这种操作应该是安全的,但是有时候类的继承关系太复杂时,可能我们直接去cast就会有问题。

那么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);
}



原创粉丝点击