Java中instanceof和isInstance的具體區別
在Think in Java泛型這一章遇到這個問題,一些博客模糊提到了isInstance是instanceof的動態實現,查閱文檔參考SOF上的一些回答如下:
- obj.instanceof(class)
表示對象obj是否是class類或其子類的對象
- 一個對象是自身類的一個對象
- 一個對象是自身類父類和接口的一個對象
- 所有對象都是Object類的對象
- 凡是null有關的都是false
- class.isInstance(obj)
文檔中這樣描述
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/15757014/isinstance-instanceof-why-theres-no-generic-way