美文网首页
isAssignableFrom理解

isAssignableFrom理解

作者: 竖起大拇指 | 来源:发表于2022-05-05 11:31 被阅读0次

isAssignableFrom方法是native方法,它的作用是用来判断两个类的之间的关联关系,也可以说是一个类是否可以被强制转换为另外一个实例对象:

 /**
     * 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 boolean isAssignableFrom(Class<?> cls) {
        if (this == cls) {
            return true;  // Can always assign to things of the same type.
        } else if (this == Object.class) {
            return !cls.isPrimitive();  // Can assign any reference to java.lang.Object.
        } else if (isArray()) {
            return cls.isArray() && componentType.isAssignableFrom(cls.componentType);
        } else if (isInterface()) {
            // Search iftable which has a flattened and uniqued list of interfaces.
            Object[] iftable = cls.ifTable;
            if (iftable != null) {
                for (int i = 0; i < iftable.length; i += 2) {
                    if (iftable[i] == this) {
                        return true;
                    }
                }
            }
            return false;
        } else {
            if (!cls.isInterface()) {
                for (cls = cls.superClass; cls != null; cls = cls.superClass) {
                    if (cls == this) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

翻译过来注释中对方法的解释就是:

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

a对象所对应类信息是b对象所对应的类信息的父类或者是父接口,简单理解即a是b的父类或接口
a对象所对应类信息与b对象所对应的类信息相同,简单理解即a和b为同一个类或同一个接口

相关文章

网友评论

      本文标题:isAssignableFrom理解

      本文链接:https://www.haomeiwen.com/subject/navnyrtx.html