2015-07-11 16 views
0

我已經跌進了以下問題,在那裏我有重載方法doSomething(),這需要一個BooleanObject,我打電話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 
    } 
} 

回答

0

這種現象的原因是因爲通用的返回類型。

public <T> T returnSomething() { 
    return null; 
} 

將任何類型從類型系統的角度看需要和總是會選擇最具體的類型,如果這是可能的「回報」。這就是爲什麼:

  1. 它會挑Boolean在第一個例子(Boolean是更具體的類型比Object
  2. 不會在你的第二個例子編譯(BooleanInteger不在同一類型層次結構等無其中更具體)