2012-11-05 77 views
1

這是<String, Void, Bitmap>下面的代碼是什麼?我甚至不知道甚至調用了這個語法。Java泛型 - 這是什麼語法?

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

它在java中被稱爲['Generics'](http://docs.oracle.com/javase/tutorial/java/generics/),其中''是類型參數 –

+0

閱讀泛型類http: //www.tutorialspoint.com/java/java_generics.htm – leonbloy

+2

夥計們!這不是一個壞問題。 –

回答

6
AsyncTask<String, Void, Bitmap> 

告知的AsyncTask由3種不同的類型,String作爲第一個參數所描述的,空隙,例如第二參數和位圖作爲第三個參數,當您使用AsyncTask時。

在java中,這被稱爲Generics,從Java5開始引入。請閱讀tutorial以瞭解有關泛型的更多信息。這裏是javadoc關於android AsyncTasktask如何使用泛型。

更新:從的javadoc的AsyncTask

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. 
+0

這不完全準確,下面的答案更準確。這三個參數是用於執行類型(String),發佈進度類型(Void/none),結果類型(Bitmap)。 – debracey

+0

@debracey:哪部分不準確?我認爲我的描述與您的描述幾乎完全相同,並添加了到AsyncTask的鏈接。剛剛更新了什麼1,2,3站立也。 – kosa

+0

您的第一句話的措詞使它聽起來像AsyncTask是一種方法,它需要三個參數,特別是單詞「調用」。這是什麼讓它感覺不準確。 – Affe

0

的AsyncTask是一個通用類。您應該查看generics tutorial以瞭解泛型的語法和語義。

如果你看看AsyncTask docs你會看到每個參數意味着什麼。

  • 第一個標記爲「params」,是doInBackground方法接受的類型。
  • 第二個是用於表示進度的類型,如onProgressUpdate方法中所採用的。
  • 第三個是結果類型的任務,即從doInBackground返回並由onPostExecute接收的類型。
2

它叫做Generics。下面是從AsyncTask manual細節:

由異步任務中使用的三種類型的有以下幾種:

PARAMS,在執行時發送給任務的參數的類型。

進度,在後臺計算期間發佈的進度單位的類型。

結果,後臺計算結果的類型。 並非所有類型總是由異步任務使用。

要標記類型爲未使用,只需使用類型空隙:

所以AsyncTask<String, Void, Bitmap>意味着,AsyncTask --DownloadImageTask接受PARAM作爲StringProgress類型爲unused,並返回其結果作爲Bitmap