【问题标题】:Generic types java泛型类型 java
【发布时间】:2016-11-07 09:22:10
【问题描述】:

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

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

那么DEBUG日志就是:"com.application.models.Custom$Response&lt;com.application.models.User&gt;" 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;
        }
    }
}

这就是我所说的 Main..

    public class User
{
    public int Id;

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

【问题讨论】:

  • 你的意思是什么,由于某种原因,当我在创建自定义时编译 T 仍然是通用的
  • 我假设Main&lt;User&gt; main = new User&lt;&gt;(); 是一个错字,应该是Main&lt;User&gt; main = new Main&lt;&gt;();,对吧?
  • 是的,我更新了答案
  • 我没有发现任何问题(除了 User 类中缺少 class 关键字和 IOnSuccess(List&lt;User&gt; list) 中缺少返回类型。哦,您可能想更改 new ArrayList()new ArrayList&lt;&gt;()
  • 很奇怪,我不断收到 com.application.testing.Custom 如果我在自定义中使用 Main 中的“T”

标签: java android generics methods


【解决方案1】:

Java 主要使用编译时泛型,这意味着当您编译时,您的泛型就消失了。它们只是编译时检查。这是否回答你的问题?谷歌类型擦除。

【讨论】:

  • 所以我不能使用final Custom&lt;T&gt; _custom = new Custom&lt;&gt;(model); ?
  • 除非 T 是已声明的类,否则该语法将不起作用。定义类或方法时可以使用泛型的抽象。当实例化一个类时,你要么指定类型,要么使用类型推断来推断类型。
  • 我写了声明的类,但没有看到“类 T{.....”。 new Custom(model) 将实例化一个 Custom。 Custom 不能分配给它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多