【问题标题】:Android Retrofit2 generics methodAndroid Retrofit2 泛型方法
【发布时间】:2020-04-14 09:46:48
【问题描述】:

我使用Retrofit2连接服务器,

为了简化请求方法的数量,我使用了泛型。但问题是改造不接受泛型方法。我把示例代码放在下面。有谁知道解决办法吗?

照片 1):

APIInterface

import io.reactivex.Observable
import okhttp3.RequestBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path

interface APIInterface {

   @POST("{url}") fun <T> post(
      @Path("url") url: String,
      @Body body: RequestBody
   ): Observable<T>

   @GET("{url}") fun <T> get(
      @Path("url") url: String
   ): Observable<T>
}

照片 2:

APIService

import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import java.io.Serializable

class APIService constructor(private val mApi: APIInterface) {

   fun <T: Serializable> post(url: String, body: RequestBody): Observable<T>{
      val observable = mApi.post<T>(url, body)
      observable.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
      return observable
   }

   fun <T: Serializable> get(url: String): Observable<T> {
      val observable = mApi.get<T>(url)
      observable.subscribeOn(Schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
      return observable
   }
}

照片 3:

call in controller

mAPIService.post<SignUpModel>(URL_SIGN_UP, body)
        .subscribe(object : APIObserver<SignUpModel> {
            override fun onNext(it: SignUpModel) {
    .
    .
    .

照片 4:

crash :(

W: java.lang.IllegalArgumentException: Method return type must not include a type variable or wildcard: io.reactivex.Observable<T>
W: for method APIInterface.post
    .
    .
    .

【问题讨论】:

  • 将您的代码添加为 text.not screenshots
  • 请不要发布图片。 insted 添加代码以便更好地理解
  • 你又可以看到了。 @DilanAnuruddha
  • 你又可以看到了。 @Parth
  • 你可以使用Observable&lt;Any&gt;

标签: java android generics kotlin retrofit2


【解决方案1】:

需要在运行时完全了解类型信息,以便 反序列化工作。

你不能这样做,类型信息需要是完全静态的而不是通用的,否则改造无法正确生成服务。看here

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2016-12-24
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多