Class的isAssignableFrom方法详解

类的Class实例中有一个isAssignableFrom方法,这个方法是用来判断两个类的之间的关联关系,也可以说是一个类是否可以被强制转换为另外一个实例对象,源码如下:

 /**
     * 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}.
     *
     * 

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 The Java Language * Specification, 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语言编写的,JDK方法的注解翻译后如下:

有两个Class类型的类象,一个是调用isAssignableFrom方法的类对象(后称对象A),以及方法中作为参数的这个类对象(称之为对象B),这两个对象如果满足以下条件则返回true,否则返回false:

  • A对象所对应类信息是B对象所对应的类信息的父类或者是父接口,简单理解即A是B的父类或接口

  • A对象所对应类信息与B对象所对应的类信息相同,简单理解即A和B为同一个类或同一个接口
    如下测试代码示例:

        Class clazz1 = Map.class;
        Class clazz2 = HashMap.class;
        Class clazz3 = List.class;
        boolean f = clazz1.isAssignableFrom(clazz2);
        System.out.println(f);//TRUE
        boolean f1 = clazz1.isAssignableFrom(clazz1);
        System.out.println(f1);//TRUE
        boolean f3 = clazz1.isAssignableFrom(clazz3);
        System.out.println(f3);//FALSE

你可能感兴趣的:(【Java】)