如何在OkHttp拦截器中获取方法的返回类型?

huangapple go评论63阅读模式
英文:

How to get method's return type in OkHttp Interceptor?

问题

通过 `okhttp3.Request#tag(Invocation::class.java)`,我们可以获取 `methodName``annotations`等信息有没有办法使用 `Invocation` 类获取方法的返回类型

我尝试过

- `request.tag(Invocation::class.java)!!.method().returnType`
- `request.tag(Invocation::class.java)!!.method().genericReturnType`

但是它们都只会返回 `class java.lang.Object`,即使实际上是一个 `List`

# 预期输出

```kotlin
@GET("products")
suspend fun getProducts(): List<Product>  // 我需要至少将 `List` 作为字符串获取此方法的返回类型

@GET("product")
suspend fun getProduct(): Product // 我需要至少将 `Object` 作为字符串获取此方法的返回类型
英文:

Via okhttp3.Request#tag(Invocation::class.java), we can get methodName, annotations etc. Is there any way to get the method's return type using Invocation class.

I've tried

  • request.tag(Invocation::class.java)!!.method().returnType
  • request.tag(Invocation::class.java)!!.method().genericReturnType

but both of them simply return class java.lang.Object, even it's a List.

Expected Output

@GET(&quot;products&quot;)
suspend fun getProducts(): List&lt;Product&gt;  // I need to get at least `List` as a String for this method

@GET(&quot;product&quot;)
suspend fun getProduct(): Product // I need to get at least `Object` as a String for this method

答案1

得分: 2

这是一个挂起函数,因此java.lang reflect.Method的返回类型不是您声明的返回类型。查看反编译的字节码,您会看到Java方法以及声明的返回类型最终出现在签名中。

英文:

It's a suspend function so the return type of the java.lang reflect.Method is not the return type you declared. Look a the decompiled bytecode and you'll see the Java method and where the declared return type ends up in the signature.

huangapple
  • 本文由 发表于 2020年7月26日 02:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63092137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定