2011-12-02 53 views
3

我被引導認爲java編譯器在編譯時做了所有方法選擇的工作(或者我錯了嗎?)。也就是說,它會通過檢查類層次結構和方法簽名來確定在編譯時在哪個類中使用哪種方法。在運行時需要的全部內容是選擇要調用其方法的對象,並且這隻能在繼承鏈上運行向上編譯時的方法選擇。如果參數可以有幾種類型呢?

如果是這樣的話,這是如何工作的?

int action = getAction(); 
StringBuilder s = new StringBuilder() 
    .append("Hello ") // Fine 
    .append(10) // Fine too 
    .append(action == 0 ? "" : action); // How does it do this? 

這裏,參數的類型可以是Stringint。在編譯時如何決定應調用StringBuilder哪種方法?

回答

4

的表達式如

action == 0 ? "" : action 

可以具有單個返回類型。編譯器將此理解爲一個返回Object實例的表達式。這在運行時可以是StringInteger

在你的情況下,append(Object)將被調用。然後StringBuilder實現將在參數上調用toString(),這會給您預期的結果(""或轉換爲字符串的整數值)。

+0

這很有道理。隱藏的autobox是唯一的副作用。 – OldCurmudgeon

0

StringBuilder有許多稱爲append的重載方法。所以大多數類型都有不同的附加。任何其他類型都是對象。

StringBuilder append(boolean b) 
Appends the string representation of the boolean argument to the sequence. 
StringBuilder append(char c) 
Appends the string representation of the char argument to this sequence. 
StringBuilder append(char[] str) 
Appends the string representation of the char array argument to this sequence. 
StringBuilder append(char[] str, int offset, int len) 
Appends the string representation of a subarray of the char array argument to this sequence. 
StringBuilder append(CharSequence s) 
Appends the specified character sequence to this Appendable. 
StringBuilder append(CharSequence s, int start, int end) 
Appends a subsequence of the specified CharSequence to this sequence. 
StringBuilder append(double d) 
Appends the string representation of the double argument to this sequence. 
StringBuilder append(float f) 
Appends the string representation of the float argument to this sequence. 
StringBuilder append(int i) 
Appends the string representation of the int argument to this sequence. 
StringBuilder append(long lng) 
Appends the string representation of the long argument to this sequence. 
StringBuilder append(Object obj) 
Appends the string representation of the Object argument. 
StringBuilder append(String str) 
Appends the specified string to this character sequence. 
StringBuilder append(StringBuffer sb) 
相關問題