Java Generics – 这个语法是什么?

下面代码的这一部分是什么意思? 我甚至都不知道甚至调用了这种语法。

 private class DownloadImageTask extends AsyncTask { } 

这是原始代码(从这里找到: 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 { /** 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 

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

这在Java中称为Generics ,从Java5开始引入。 请阅读本教程以了解有关generics的更多信息。 这是关于android AsyncTasktask如何使用generics的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手册中的详细信息:

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

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

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

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

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

所以AsyncTask意味着, AsyncTask --DownloadImageTask接受param为StringProgress类型unused并返回结果为Bitmap

AsyncTask是一个通用类。 您应该查看generics教程以了解generics的语法和语义。

如果查看AsyncTask文档,您将看到每个参数的含义。

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