2010-01-28 20 views
4
Long l1 = null; 
Long l2 = Long.getLong("23"); 
Long l3 = Long.valueOf(23); 

System.out.println(l1 instanceof Long); // returns false 
System.out.println(l2 instanceof Long); // returns false 
System.out.println(l3 instanceof Long); // returns true 

我無法理解返回的輸出。我期待真正的第二和第三系統的至少。有人可以解釋instanceof如何工作嗎?關於instanceof的工作問題

+0

爲什麼你需要完整的代碼呢? – GuruKulki 2010-01-28 11:09:42

+1

你應該做'System.out.println(l1); ...'等,這會告訴你發生了什麼。 – pstanton 2010-01-28 11:10:10

+0

對於l2,或許您應該使用Long.parseLong(String) 請參見 2010-01-28 15:41:56

回答

11

l1 instanceof Long

因爲l1的instanceof產量(如由Java的語規格指定)

l2 instanceof Long

這會產生因爲你使用了錯誤的方法getLong

Determines the long value of the system property with the specified name.

+0

請參閱http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Long.html#getLong%28java.lang。String%29 – 2010-01-28 11:25:01

+0

啊,醜陋的oracle favicon現在在javadoc上。爆破。 – Bozho 2010-01-28 11:26:56

14

這有什麼好做instanceof。方法Long.getLong()不解析字符串,它返回具有該名稱的系統屬性的內容,解釋爲long。由於沒有名稱爲23的系統屬性,它將返回null。你想要Long.parseLong()

+0

(增加了一個缺失的撇號) – Bozho 2010-01-28 11:13:07

+0

@Bozho:謝謝:) – 2010-01-28 11:42:31

6

Long.getLong(..)返回系統屬性的長整型值。它返回null您的情況,因爲沒有名爲「23」的系統屬性。所以:

  • 1和2是nullinstanceof回報false比較空
  • 3時java.lang.Long(你可以通過輸出l3.getClass()檢查),以便true預計

而不是使用Long.getLong(..)的,使用Long.parseLong(..)解析String

+0

+1。很好的答案 – dfa 2010-01-28 11:10:32

0

該實例將檢查被檢查對象的類型。

在你的頭兩個將有空值,它返回false。而第三個具有返回true的Long對象。

您可以在這個Java詞彙網站獲得instaceof更多的信息:http://mindprod.com/jgloss/instanceof.html

1

我想一個可以改寫SOP的是:

System.out.println(l1 != null && l1 instanceof Long); 
System.out.println(l2 != null && l2 instanceof Long); 
System.out.println(l3 != null && l3 instanceof Long); 

一如往常null不能爲instanceof什麼。