2015-09-05 18 views
0

我學習Java,我不明白爲什麼下面的代碼不會沒有錯誤編譯:使用的instanceof方法對原始類型的Java提供了編譯器錯誤

public class SecondClass{ 

public static void main(String[] args){ 
    int number = 45; 
    if (number instanceof String) { 
     System.out.println("Not a String!"); 
    } 
    } 
} 

爲什麼我在我的條件的操作中得到一個錯誤? instanceof應該返回truefalse對不對?在這種情況下,應該有false,因爲numberint,但此代碼不能編譯。

+1

http://stackoverflow.com/questions/12361492/how-to-determine-the-primitive-type -a-primitive-variable進一步的解釋在這裏。 instanceof僅用於對象。 – CollinD

回答

6

section 15.20.2 of the JLS

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

在你的情況下,RelationalExpression操作數的情況下int,所以你會得到一個編譯時錯誤。

即使你有Integer類型的表達式,你再碰上:

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

相關問題