【问题标题】:Java Generics - What is this syntax for?Java 泛型 - 这个语法有什么用?
【发布时间】:2012-11-05 18:32:16
【问题描述】:

<String, Void, Bitmap> 下面这部分代码是什么意思?我什至不知道这个语法叫什么。

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

}



这是原始代码(从这里找到:http://developer.android.com/guide/components/processes-and-threads.html):

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}

【问题讨论】:

标签: java android generics


【解决方案1】:
AsyncTask<String, Void, Bitmap>

当你使用 AsyncTask 时,告诉 AsyncTask 由 3 种不同的类型描述,String 作为第一个参数,Void 作为第二个参数,Bitmap 作为第三个参数。

这在 java 中称为Generics,从 Java5 开始引入。请阅读此tutorial 以了解有关泛型的更多信息。这里是javadoc,关于 android AsyncTasktask 如何使用泛型。

更新:来自 AsyncTask javadoc

1) Params, the type of the parameters sent to the task upon execution.
2) Progress, the type of the progress units published during the background computation.
3) Result, the type of the result of the background computation.

【讨论】:

  • 这并不完全准确,下面的答案更准确。三个参数分别是执行类型(String)、发布进度类型(Void/none)、结果类型(Bitmap)。
  • @debracey:哪一部分不准确?我认为我的描述与您的描述几乎完全相同,并添加了指向 AsyncTask 的链接。刚刚更新了 1,2,3 代表的内容。
  • 第一句话的措辞听起来像是 AsyncTask 是一个接受三个参数的方法,尤其是“调用”这个词。这就是让它感觉不准确的原因。
  • @Affe:将调用改为使用,现在有意义吗?
  • 正如@Affe 指出的那样,这并不是真正的“接受参数”,这听起来像是一个方法调用,但事实并非如此。更好的措辞可能是“包含”或“由 3 种不同类型描述”——类似这样。这是一件小事,我认为你的澄清很好。
【解决方案2】:

它叫做Generics。以下是来自AsyncTask manual的详细信息:

异步任务使用的三种类型如下:

Params,执行时发送给任务的参数类型。

Progress,后台计算时发布的进度单位类型。

Result,后台计算结果的类型。 并非所有类型都始终由异步任务使用。

要将类型标记为未使用,只需使用类型 Void:

所以AsyncTask&lt;String, Void, Bitmap&gt; 表示AsyncTask --DownloadImageTask 接受参数为StringProgress 类型为unused 并返回结果为Bitmap

【讨论】:

    【解决方案3】:

    AsyncTask 是一个泛型类。您应该查看generics tutorial 以了解泛型的语法和语义。

    如果您查看AsyncTask docs,您将了解每个参数的含义。

    • 第一个标记为“params”,是您的 doInBackground 方法接受的类型。
    • 第二个是用于表示进度的类型,在 onProgressUpdate 方法中采用。
    • 第三个是任务的结果类型,从 doInBackground 返回并由 onPostExecute 接收的类型。

    【讨论】:

      猜你喜欢
      • 2011-01-23
      • 2021-07-09
      • 2012-08-29
      • 1970-01-01
      • 2016-08-03
      • 2011-05-17
      • 2021-07-27
      • 1970-01-01
      • 2012-12-06
      相关资源
      最近更新 更多