Java Generics - 这个语法是什么?

时间:2012-11-05 18:32:16

标签: java android generics

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

3 个答案:

答案 0 :(得分:6)

AsyncTask<String, Void, Bitmap>

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

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

更新:来自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.

答案 1 :(得分:2)

它被称为Generics。以下是AsyncTask manual

的详细信息
  

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

     

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

     

进度,后台计算期间发布的进度单元的类型。

     

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

     

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

所以AsyncTask<String, Void, Bitmap>表示AsyncTask --DownloadImageTask接受参数为StringProgress类型为unused并将结果返回为Bitmap < / p>

答案 2 :(得分:0)

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

如果查看AsyncTask docs,您会看到每个参数的含义。

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