天天看點

深入Java關鍵字instanceof

instanceof關鍵字用于判斷一個引用類型變量所指向的對象是否是一個類(或接口、抽象類、父類)的執行個體。

instanceof是Java的一個二進制操作符,和==,>,<是同一類東東。由于它是由字母組成的,是以也是Java的保留關鍵字。它的作用是測試它左邊的對象是否是它右邊的類的執行個體,傳回boolean類型的資料。

  舉個例子:   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。