最近在java的源代码中总是可以看到
isAssignableFrom()
这个方法,到底是干嘛的?怎么用?
1. 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);
用native
关键字描述,说明是一个底层方法,实际上是使用c/c++实现的,java里面没有实现,那么这个方法是干什么的呢?我们从上面的注释可以解读:
如果是A.isAssignableFrom(B)
确定一个类(B)是不是继承来自于另一个父类(A),一个接口(A)是不是实现了另外一个接口(B),或者两个类相同。主要,这里比较的维度不是实例对象,而是类本身,因为这个方法本身就是Class
类的方法,判断的肯定是和类信息相关的。
也就是判断当前的Class对象所表示的类,是不是参数中传递的Class对象所表示的类的父类,超接口,或者是相同的类型。是则返回true,否则返回false。
2.代码实验测试
2.1 父子继承关系测试
class A{
}
class B extends A{
}
class C extends B{
}
public class test {
public static void main(String[] args) {
A a = new A();
B b = new B();
B b1 = new B();
C c = new C(