標籤:模糊 operator 描述 method UI post etc AC val
Java中instanceof和isInstance的具體區別
在Think in Java泛型這一章遇到這個問題,一些部落格模糊提到了isInstance是instanceof的動態實現,查閱文檔參考SOF上的一些回答如下:
表示對象obj是否是class類或其子類的對象
- 一個對象是自身類的一個對象
- 一個對象是自身類父類和介面的一個對象
- 所有對象都是Object類的對象
- 凡是null有關的都是false
文檔中這樣描述
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.
即對象obj能否轉化為類class的對象,動態等價於instanceof
- 一個對象能轉化為自身類的對象
- 一個對象能被轉化為自身類的父類和實現的介面的對象
- 所有對象都能轉化為Object類的對象
- 凡是null有關的都是false
可見與instanceof用法相同,關鍵在於動態等價
class Father{}class Son extends Father{}public class Test{ public static boolean DynamicEqual(Object fatherObj,Object sonObj){ return fatherObj.getClass().isInstance(sonObj); // pass // return sonObj instanceof Father; // pass // return sonObj instanceof (fatherObj.getClass()); //error } public static void main(String[] args){ //same using Father father = new Father(); Son son = new Son(); System.out.println(son instanceof Son); // true System.out.println(son instanceof Father); // true System.out.println(son instanceof Object); // true System.out.println(null instanceof Object); // false System.out.println(); System.out.println(Son.class.isInstance(son)); // true System.out.println(Father.class.isInstance(son)); // true System.out.println(Object.class.isInstance(son)); // true System.out.println(Object.class.isInstance(null)); // false System.out.println(); //different using System.out.println(DynamicEqual(father, son)); }}
對obj.instanceof(class),在編譯時間編譯器需要知道類的具體類型
對class.isInstance(obj),編譯器在運行時才進行類型檢查,故可用於反射,泛型中
參考:
https://stackoverflow.com/questions/8692214/when-to-use-class-isinstance-when-to-use-instanceof-operator
https://stackoverflow.com/questions/15757014/isinstance-instanceof-why-theres-no-generic-way
http://blog.csdn.net/u010002184/article/details/79306195
Java中instanceof和isInstance的具體區別