2012-11-21 34 views
31

instanceof可用於測試對象是給定類的直接或下降實例。 instanceof也可以與接口一起使用,即使接口不能像類一樣實例化。任何人都可以解釋instanceof是如何工作的?instanceof將如何在接口上工作

回答

44

首先,我們可以存儲的實現在interface reference variable這樣一個特定的interfaceinstances

package com.test; 

public class Test implements Testeable { 

    public static void main(String[] args) { 

     Testeable testeable = new Test(); 

     // OR 

     Test test = new Test(); 

     if (testeable instanceof Testeable) 
      System.out.println("instanceof succeeded"); 
     if (test instanceof Testeable) 
      System.out.println("instanceof succeeded"); 
    } 
} 

interface Testeable { 

} 

即,實現特定接口將通過instanceof測試

EDIT

和輸出

instanceof succeeded 
instanceof succeeded 

@RohitJain任何運行時實例

您可以通過使用這樣的

Runnable runnable = new Runnable() { 

    public void run() { 
     System.out.println("inside run"); 
    } 
}; 

匿名內部類創建的接口實例和你測試實例類型的接口,使用instanceof運營商這樣

System.out.println(runnable instanceof Runnable); 

,其結果是「真」

+0

你可能在你的條件下表示'instanceof Test'。 –

+0

nope ..問題是關於使用'instanceof'對'interface'。 rt? – sunil

+0

@sunil ..是的,這是真的。但是如果你用一個接口檢查'instanceof',你總會得到錯誤的結果。由於您無法創建接口的實例,因此檢查引用是否指向它的實例並不重要。我希望你得到我想說的話。 –

-1

instanceof運算符會告訴您第一個參數是否是實現第二個參數的對象。不明白爲什麼它不能直接實例化接口。

Integer num = 1; 
if (num instanceof Number) { 
    System.out.println("An integer is a number!"); 
} 

這就是你所需要的。

+0

您的示例缺少問題的重點 - 整數_extends_(不實現)數字。 –

5

你做一個instanceof檢查一個reference的針對instance,它檢查的instance特定reference所指向的類型。

現在,因爲你可以創建一個interface的一個參考,它指向執行class(相同的概念,Super class reference指向subclass instance)的一個實例。因此,您可以對其執行instanceof檢查。

對於e.g: -所有的

public interface MyInterface { 
} 

class ImplClass implements MyInterface { 

    public static void main(String[] args) { 
     MyInterface obj = new ImplClass(); 

     System.out.println(obj instanceof ImplClass); // Will print true. 
    } 
} 
+3

什麼?當然'(obj instanceof ImplClass)== true',obj class是ImplClass!問題是,'(obj instanceof MyInterface)== true'?我猜這是一個錯字。這個解釋有點混亂。 –

2

-首先使用instanceof來比較持有對象的對象引用變量是否具有某種類型。

例如:

public void getObj(Animal a){  // a is an Object Reference Variable of type Animal 

    if(a instanceof Dog){ 


     } 

} 

-interface的情況下,其實現它可以與instanceof使用的class

如:

public interface Brush{ 

    public void paint(); 
} 

public class Strokes implements Brush{ 

     public void paint(){ 

      System.out.println("I am painting"); 

    } 


} 

public class Test{ 


    public static void main(String[] args){ 

      Brush b = new Strokes(); 

     if(b instanceof Strokes){ 


      b.paint(); 
     } 
    } 

} 
2

喜下面將產生真正的instanceof的:

• If S is an ordinary (nonarray) class, then: 
    • If T is a class type, then S must be the same class as T, or S must be a subclass of T; 
    • If T is an interface type, then S must implement interface T. 
• If S is an interface type, then: 
    • If T is a class type, then T must be Object. 
    • If T is an interface type, then T must be the same interface as S or a superinterface of S. 
• If S is a class representing the array type SC[], that is, an array of components of type SC, then: 
    • If T is a class type, then T must be Object. 
    • If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3). 
• If T is an array type TC[], that is, an array of components of type TC, then one of the following must be true: 
     - TC and SC are the same primitive type. 
     - TC and SC are reference types, and type SC can be cast to TC by these run-time rules 

請到這個環節有清晰的思路:

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.instanceof

2
public class Programmers { 

    public static boolean hasReallife(Programmer programmer) { 
     return programmer instanceof Reallife; ══════════════════╗ 
    }               ║ 
                   ║ 
}                ║ 
                   ▼ 
public class ReallifeProgrammer extends Programmer implements Reallife { 

    public ReallifeProgrammer() { 
     diseases.get("Obesity").heal(); 
     diseases.get("Perfectionism").heal(); 
     diseases.get("Agoraphobia").heal(); 
    } 

    @Override 
    public void goOut() { 
     house.getPC().shutDown(); 
     wife.argue(); 
    } 

    @Override 
    public void doSports() { 
     goOut(); 
     BigWideWorld.getGym("McFit").visit(); 
    } 

    @Override 
    public void meetFriends() { 
     goOut(); 
     BigWideWorld.searchFriend().meet(); 
    } 

} 
+0

好ascii藝術! – winklerrr

0

我知道這是一個非常非常古老的問題,有很多很好的答案。我只想指出最簡單的方法(至少對我來說是最簡單的方法)來理解這個操作符。

如果o instanceof t回報true,然後 t castedObj = (t) o;不會拋出ClassCastException,並且castedObj不會null

如果您稍後要從castedObj訪問字段或方法,那麼這很重要/有用 - 您知道通過執行instanceof檢查後,您將不會再遇到問題。

唯一的缺點是,這可以用於沒有泛型的類型。