Oll*_*e C 5 android kotlin retrofit2 kotlin-reflect
给定这样的接口方法(Android Retrofit),如何在运行时从 Kotlin 代码中读取注释参数中指定的 URL 路径?
Api定义接口:
@GET("/api/somepath/objects/")
fun getObjects(...)
Run Code Online (Sandbox Code Playgroud)
读取注释值:
val method = ApiDefinition::getObjects.javaMethod
val verb = method!!.annotations[0].annotationClass.simpleName ?: ""
// verb contains "GET" as expected
// But how to get the path specified in the annotation?
val path = method!!.annotations[0].????????
Run Code Online (Sandbox Code Playgroud)
更新1
感谢您的回答。我仍然在挣扎,因为我看不到使用什么类型来执行以下操作:
val apiMethod = ApiDefinition::getObjects
Run Code Online (Sandbox Code Playgroud)
....然后将该函数引用传递给这样的方法(它被重用)
private fun getHttpPathFromAnnotation(method: Method?) : String {
val a = method!!.annotations[0].message
}
Run Code Online (Sandbox Code Playgroud)
IntelliJ IDE 建议我使用 KFunction5<> 作为函数参数类型(据我所知,它不存在),并且似乎要求我也指定该方法的所有参数类型,这会进行通用调用以获取注释属性不可能。Kotlin 中是否有一个相当于“Method”的类型?一种可以接受任何方法的类型?我尝试了 KFunction,但没有成功。
更新2
感谢您澄清事情。我已经到了这一点:
ApiDefinition(改造接口)
@GET(API_ENDPOINT_LOCATIONS)
fun getLocations(@Header(API_HEADER_TIMESTAMP) timestamp: String,
@Header(API_HEADER_SIGNATURE) encryptedSignature: String,
@Header(API_HEADER_TOKEN) token: String,
@Header(API_HEADER_USERNAME) username: String
): Call<List<Location>>
Run Code Online (Sandbox Code Playgroud)
检索注释参数的方法:
private fun <T> getHttpPathFromAnnotation(method: KFunction<T>) : String {
return method.annotations.filterIsInstance<GET>().get(0).value
}
Run Code Online (Sandbox Code Playgroud)
调用以获取特定方法的路径参数:
val path = getHttpPathFromAnnotation<ApiDefinition>(ApiDefinition::getLocations as KFunction<ApiDefinition>)
Run Code Online (Sandbox Code Playgroud)
隐式转换似乎是必要的,或者类型参数要求我提供 KFunction5 类型。
这段代码可以工作,但是它有硬编码的 GET 注释,有没有办法让它更通用?我怀疑我可能需要查找 GET、POST 和 PUT 并返回第一个匹配项。
直接使用 Kotlin而不是(无论如何你都在使用 Kotlin!),并且KFunction javaMethodfindAnnotation获得简洁、惯用的代码。
如果注释碰巧不是第一个注释,这也将起作用,因为注释annotations[0]可能会中断。
val method = ApiDefinition::getObjects
val annotation = method.findAnnotation<GET>() // Will be null if it doesn't exist
val path = annotation?.path
Run Code Online (Sandbox Code Playgroud)
基本上findAnnotation所做的就是返回
annotations.filterIsInstance<T>().firstOrNull()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8152 次 |
| 最近记录: |