使用reflection读取Kotlin函数注释值?
给定一个像这样的接口方法(Android Retrofit),如何在运行时从Kotlin代码读取注解参数中指定的URL路径?
ApiDefinition接口:
@GET("/api/somepath/objects/") fun getObjects(...)
阅读注释值:
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].????????
更新1
感谢您的回答。 我还在苦苦挣扎,因为我看不到要使用什么types来执行以下操作:
val apiMethod = ApiDefinition::getObjects
….然后将该函数引用传递到这样的方法(它被重用)
private fun getHttpPathFromAnnotation(method: Method?) : String { val a = method!!.annotations[0].message }
IntelliJ IDE是建议我使用KFunction5 作为函数参数类型(它不存在,据我所知),似乎是要求我指定的方法的所有参数类型,这使得泛型调用获得注释属性不可能。 是不是有一个“方法”的Kotlin相当于一个类型,将接受任何方法? 我尝试了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>
检索注释参数的方法:
private fun getHttpPathFromAnnotation(method: KFunction) : String { return method.annotations.filterIsInstance().get(0).value }
调用以获取特定方法的路径参数:
val path = getHttpPathFromAnnotation(ApiDefinition::getLocations as KFunction)
隐式转换似乎是必要的,或者types参数要求我提供一个KFunction5types。
这段代码可以工作,但是它的GET注解是硬编码的,有没有办法使它更通用? 我怀疑我可能需要查找GET,POST和PUT并返回第一个匹配。
直接使用Kotlin KFunction
而不是javaMethod
(无论你使用Kotlin!),还是使用findAnnotation
来获得简洁,惯用的代码。
如果注释不是第一个annotations[0]
可能中断,这也将起作用。
val method = ApiDefinition::getObjects val annotation = method.findAnnotation() // Will be null if it doesn't exist val path = annotation?.path
基本上所有findAnnotation
所做的都是返回
annotations.filterIsInstance().firstOrNull()