2013-04-28 60 views
1

我有點困惑與下面的代碼。問題是代碼看起來與列表< T>具有與T相同的類型。 考慮方法makeList接收類型DTOInt的參數< T>並返回列表< T>(列表T)。 類DTO執行「T getData()方法」 DTOInt < T>的,所以我們必須DTOInt接口具有一般定義t內是返回類型getData()方法的。鑄造普通的T列出<T>

所以,內部makeList方法我做方法的getData()返回的對象(其是T形)的明顯鑄造成列表< T>。 它編譯和運行良好。

關於編制了明確的 - 有一個明顯的鑄件,但是當它運行怎麼不失敗,拋出ClassCastException上鑄造線在makeList()方法?

interface DTOInt<T>{ 
    T getData(); 
} 

class DTO implements DTOInt<List<List<String[]>>>{ 
    public List<List<String[]>> getData() { 
     String[] arr = {"1.1","1.2","1.3"}; 
     String[] arr1 = {"2.1","2.2","2.3"}; 

     List<String[]> l = new ArrayList<String[]>(); 

     l.add(arr); 
     l.add(arr1); 

     List<List<String[]>> data = new ArrayList<List<String[]>>(); 
      data.add(l); 

     return data; 
    } 

} 

public class Test { 

    static <T> List<T> makeList(DTOInt<T> inp){ 
     T data = inp.getData(); 
     List<T> list = (List<T>) data; 
     return list; 
    } 

    public static void main(String[] args) { 
     System.out.println(makeList(new DTO())); 
    } 
} 

回答

3

這在運行時起作用的原因是因爲泛型在運行時不存在,它們純粹在編譯器端實現。在編譯過程中,泛型被一個名爲「type erasure」的進程刪除。

所有運行時發現的是,您的方法DTO.getData()正在返回List類型的結果。在視運行時的點 - - 這一結果是從makeList()方法,該方法返回返回List一樣,所以運行時很高興。

當然,這隻適用於因爲DTO確實返回List結果。如果你想創建一個二等

class DTO2 implements DTOInt<Integer> { ... } 

然後澆鑄DTO2.getData()List結果的確會拋出異常。

+0

謝謝ignaZ! – Nemo 2013-04-28 11:48:05