2016-11-07 74 views
0

檢查我的自定義類。如果我改變DoSomething的()來通用類型java

final Custom<User> _custom = new Custom<>(new TypeToken<Custom<User>.Response<User>>(){}, ""); 

則調試日誌:"com.application.models.Custom$Response<com.application.models.User>" serverResponse: ""

但如果DoSomething的是:

final Custom<T> _custom = new Custom<>(new TypeToken<Custom<T>.Response<T>>(){}, ""); 

調試日誌是:

"com.application.models.Custom$Response<T>" serverResponse: " 

我有這樣的班級:

public class Main 
{ 
    public static <T> void DoSomething() 
    { 
     final Custom<T> _custom = new Custom<>(new TypeToken<Custom<T>.Response<T>>(){}, ""); 
    } 
} 

//我增加了調試日誌的變量的權

public class Custom<T> 
{ 
    private TypeToken<Response<T>> _responseType; _response: null 
    private Response<T> _response; _response: null 
    private String _serverResponse; _serverResponse = null; 

    public Custom(TypeToken<Response<T>> responseType, String serverResponse) `responseType: "com.application.models.Custom$Response<T>" serverResponse: "` 
    { 
     this._responseType = responseType; 
     this._serverResponse = serverResponse; 
    } 

    public class Response<t> 
    { 
     private List<t> data = null; 

     public List<t> GetData() 
     { 
      return this.data; 
     } 
    } 
} 

這就是我所說的主要..

public class User 
{ 
    public int Id; 

    public void Test() 
    { 
     Main.<User>DoSomething(); 
    } 
} 
+0

你是什麼意思?由於某些原因,當我編譯T仍然通用時,我創建自定義*? – Blackbelt

+2

我假設'主主=新用戶<>();'是一個錯字,應該是'Main main = new Main <>();',對嗎? – Eran

+0

是的,我更新了我的答案 –

回答

0

的Java大多與編譯時泛型工作,這意味着當你編譯時,你的泛型不見了。他們只是一個編譯時檢查。這是否回答你的問題? Google類型擦除。

+0

所以我不能使用'最終自定義 _custom = new Custom <>(model); '? –

+0

除非T是已聲明的類,否則該語法將不起作用。定義類或方法時可以使用泛型的抽象。當實例化一個類時,您將指定類型或使用類型推斷來推斷類型。 –

+0

是的,但如果你檢查我的問題,我在我的方法中定義了T ... –