我已經跌進了以下問題,在那裏我有重載方法doSomething()
,這需要一個Boolean
或Object
,我打電話returnSomething()
,並通過返回值成當選擇重載具體類型doSomething()
,如下面的片斷所示:的Java似乎得到一個參數化類型
public class SomeService {
public <T> T returnSomething() {
return null;
}
public void doSomething(Boolean a) {
System.out.println("Boolean");
}
public void doSomething(Object a) {
System.out.println("object");
}
public static void main(String[] args) {
SomeService someService = new SomeService();
someService.doSomething(someService.returnSomething()); // prints Boolean
}
}
當我運行代碼它調用doSomething((Boolean))
。
由於returnSomething()
的返回類型被清除爲Object
,我預料它會調用doSomething((Object))
來代替。
有誰知道這是否如預期的行爲,它調用doSomething((Boolean))
而不是doSomething((Object))
?
我試圖改變這兩種方法的順序,看看是否重要,但它沒有。我也嘗試將Boolean
參數改爲Integer
,而且它的行爲方式相同,即它調用非對象方法。
作爲獎勵信息我還發現如果我添加一個額外的方法doSomething((Integer))
:
- 的IntelliJ 14返回以下錯誤消息:
cannot resolve method doSomething(java.lang.Object)
- Eclipse的火星返回以下錯誤消息:
the method doMethod(Boolean) is ambiguous for the type SomeService
如果我更改doSomething((Integer))
和doSomething((Boolean))
的定義順序,錯誤消息也會更改。
public class SomeService {
public <T> T returnSomething() {
return null;
}
public void doSomething(Boolean a) {
System.out.println("Boolean");
}
public void doSomething(Integer a) {
System.out.println("Integer");
}
public void doSomething(Object a) {
System.out.println("object");
}
public static void main(String[] args) {
SomeService someService = new SomeService();
someService.doSomething(someService.returnSomething()); // compilation error
}
}