由于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);
}
本文介绍如何使用Java的isAssignableFrom方法来安全地进行对象类型的转换。该方法可以有效地判断一个类是否为另一个类的子类或者实现接口,从而避免在运行时出现类型转换异常。

2127

被折叠的 条评论
为什么被折叠?



