2011-09-22 75 views
3

任何人都可以簡單地解釋爲什麼在下面的類中,當我傳遞一個字符串,整型或UUID時,只有使用Object作爲參數的方法重載?Java類型擦除和重載?

public final class SkuHydratingConverter implements Converter<Object, Sku> { 
    @Autowired 
    private SkuService skuService; 


    /** 
    * Default implementation, that errs as we don't know how to convert from 
    * the source type. 
    */ 
    public Sku convert(Object source) throws IllegalArgumentException { 
     throw new IllegalArgumentException("Could not convert to Sku"); 
    } 


    public Sku convert(String source) throws IllegalArgumentException { 
     return convert(Integer.valueOf(source)); 
    } 


    public Sku convert(Integer source) throws IllegalArgumentException { 
     return skuService.get(source); 
    } 


    public Sku convert(UUID source) throws IllegalArgumentException { 
     return skuService.get(source); 
    } 
} 

本來我想實現在一個類Converter<?, ?>三次,但我很快就發現這是不可能的。

+0

您如何訪問此方法?你能給一個代碼示例嗎? –

回答

4

重載機制在編譯時工作,即調用哪個方法在編譯類時決定,而不是在運行程序時決定。

由於運行時類型不能(通常)在編譯時已知的,這樣

Object o = "some string"; 
method(o); 

一個片段會導致對一個method,它接受一個Object作爲參數的調用,如Objectcompile-time typeo

(這有沒有關係類型擦除或仿製藥)。

0

正如其他人解釋說,這是不以力擦除但convert(Object source)在編譯時綁定的事實有關。如果在每個之前放置一個@Override,則會在其餘部分中出現錯誤,表明只有該方法重寫了超類方法。

你需要的是實際類型的運行時檢查:

public Sku convert(Object source) throws IllegalArgumentException 
{ 
    if (source instanceof String) { 
     return convert((String) source); 
    } else if (source instanceof ...) { 
    } else // none match, source is of unknown type 
    { 
     throw new IllegalArgumentException("Could not convert to Sku, unsuported type " + source.getClass()); 
    } 
} 

} 

其他convert方法應該是private

1

只有你實際執行的轉換方法是轉換(對象源),因爲你給類型參數對象中:

Converter<Object, Sku> 

與字符串和UUID參數,你只能叫另外兩個轉換的方法當你直接使用實例時(而不是通過接口)。這兩種方法不會覆蓋任何東西,它們會超載。

Converter con = new SkuHydratingConverter(); 
con.convert(new String());//calls convert(Object), it does not know about any other method 

SkuHydratingConverter con2 = new SkuHydratingConverter(); 
con2.convert(new String()); //calls convert(String), because it is one with best matching type of argument.