簡體   English   中英

Java泛型-此語法的用途是什么?

[英]Java Generics - What is this syntax for?

<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);
    }
}
AsyncTask<String, Void, Bitmap>

告訴AsyncTask使用3種不同的類型進行描述,當您使用AsyncTask時,將String作為第一個參數,將Void作為第二個參數並將Bitmap作為第三個參數。

這是從Java5開始引入的Java中的泛型 請閱讀本教程以了解有關泛型的更多信息。 這是有關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.

它稱為Generics 這是AsyncTask手冊中的詳細信息:

異步任務使用的三種類型如下:

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

Progress ,后台計算期間發布的進度單位的類型。

Result ,背景計算結果的類型。 並非所有類型都總是由異步任務使用。

要將類型標記為未使用,只需使用Void類型:

因此, AsyncTask<String, Void, Bitmap>意味着, AsyncTask --DownloadImageTask將參數接受為Stringunused Progress類型並將結果作為Bitmap返回

AsyncTask是一個通用類。 您應該看一下泛型教程,以了解泛型的語法和語義。

如果查看AsyncTask文檔,您將看到每個參數的含義。

  • 第一個標記為“參數”,並且是doInBackground方法接受的類型。
  • 第二種是用於表示進度的類型,如onProgressUpdate方法中所采用的。
  • 第三個是任務的結果類型,即從doInBackground返回並由onPostExecute接收的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM