instanceof關鍵字用於判斷一個引用類型變量所指向的對像是否是一個類(或接口、抽像類、父類)的實例。
舉個例子:
複製代碼代碼如下:
public interface IObject {
}
public class Foo implements IObject{
}
public class Test extends Foo{
}
public class MultiStateTest {
public static void main(String args[]){
test();
}
public static void test(){
IObject f=new Test();
if(f instanceof java.lang.Object)System.out.println("true");
if(f instanceof Foo)System.out.println("true");
if(f instanceof Test)System.out.println("true");
if(f instanceof IObject)System.out.println("true");
}
}
輸出結果:
複製代碼代碼如下:
true
true
true
true
另外,數組類型也可以使用instanceof來比較。比如復制代碼代碼如下:
String str[] = new String[2];
則str instanceof String[]將返回true。