Java 對(duì)象與類,對(duì)象與接口,類與接口之間的關(guān)系判斷。

(new yy()) instanceof xx.class 判斷 yy對(duì)象 否是 xx類 的實(shí)例
xx.class.isAssignableFrom(yy.class) 判斷 yy類 是否為 xx類 的子類或?qū)崿F(xiàn)

/**
 * 兩個(gè)Class判斷
 */
// 判斷對(duì)象是否為實(shí)例
ChildClass child = new ChildClass();
System.out.printf("child對(duì)象 是不是 ChildClass 的實(shí)例 %s\n", 
        child instanceof ChildClass); 
            // true

System.out.printf("child對(duì)象 是不是 FatherClass 的實(shí)例 %s\n", 
        child instanceof FatherClass); 
            // true

// 判斷類是否繼承某類
System.out.printf("FatherClass 是不是 ChildClass 的父類 %s\n", 
        FatherClass.class.isAssignableFrom(ChildClass.class)); 
            // true


/**
 * 接口和實(shí)現(xiàn)類判斷
 */
// 判斷對(duì)象是否為實(shí)例
AbstractInterfaceImpl impl = new AbstractInterfaceImpl();
System.out.printf("impl對(duì)象 是不是 AbstractInterfaceImpl 的實(shí)例 %s\n", 
        impl instanceof AbstractInterfaceImpl); 
            // true

System.out.printf("impl對(duì)象 是不是 AbstractInterface 的實(shí)例 %s\n", 
        impl instanceof AbstractInterface); 
            // true

// 判斷類是否為接口實(shí)現(xiàn)
System.out.printf("AbstractInterfaceImpl 是不是 AbstractInterface 的接口實(shí)現(xiàn) %s\n", 
        AbstractInterface.class.isAssignableFrom(AbstractInterfaceImpl.class)); 
            // true

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容