在java的源代码中总是可以看到
isAssignableFrom()
这个方法,方法是什么用呢?
首先我们必须知道的是,java里面一切皆对象,类本身也是会当成对象来处理,主要体现在类
的.class
文件,其实加载到java虚拟机之后,也是一个对象,它就是Class
对象,全限定类
名:java.lang.Class
。那这个isAssignableFrom()
其实就是Class对象的一个方法:
/**
* Determines if the class or interface represented by this
* {@code Class} object is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the specified
* {@code Class} parameter. It returns {@code true} if so;
* otherwise it returns {@code false}. If this {@code Class}
* object represents a primitive type, this method returns
* {@code true} if the specified {@code Class} parameter is
* exactly this {@code Class} object; otherwise it returns
* {@code false}.
*
* <p> Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* or via a widening reference conversion. See <em>The Java Language
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
*
* @param cls the {@code Class} object to be checked
* @return the {@code boolean} value indicating whether objects of the
* type {@code cls} can be assigned to objects of this class
* @exception NullPointerException if the specified Class parameter is
* null.
* @since JDK1.1
*/
public native boolean isAssignableFrom(Class<?> cls);
为了方便理解,先来解释一下方法名的含义:Assignable意为可分配的、可指定的,当前类可从cls类转化(分配)而来,举个例子:List类继承自Collection类,那么List类可转化为Collection类,以下代码返回ture。
Collection.class.isAssignableFrom(List.class)
再来看下源码中对该方法的注释部分:
用native
关键字描述,说明是一个底层方法,实际上是使用c/c++实现的,java里面没有实现。
如果是A.isAssignableFrom(B)
确定一个类(B)是不是继承来自于另一个父类(A),一个接口(B)是不是实现了另外一个接口(A),或者两个类相同。主要,这里比较的维度不是实例对象,而是类本身,因为这个方法本身就是Class
类的方法,判断的肯定是和类信息相关的。
也就是判断当前的Class对象所表示的类,是不是参数中传递的Class对象所表示的类的父类,超接口,或者是相同的类型。是则返回true,否则返回false。
总结:
isAssignableFrom
是用来判断子类和父类的关系的,或者接口的实现类和接口的关系的,默认所有的类的终极父类都是Object
。如果A.isAssignableFrom(B)
结果是true,证明B
可以转换成为A
,也就是A
可以由B
转换而来。