2016-11-07 75 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 ... –