通用类型java

时间:2016-11-07 09:22:10

标签: java android generics methods

检查我的自定义类。如果我将DoSomething()更改为

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

然后DEBUG日志是:"com.application.models.Custom$Response<com.application.models.User>" serverResponse: ""

但如果DoSomething是:

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

DEBUG日志是:

"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;
        }
    }
}

这就是我称之为Main ..

    public class User
{
    public int Id;

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

1 个答案:

答案 0 :(得分:0)

Java主要使用编译时泛型,这意味着当你编译时,你的泛型就不见了。它们只是编译时检查。这是否回答你的问题? Google Type Erasure。