这个问题是关于Android开发中的自定义注解(Java/Kotlin)。我想为方法及其参数创建自定义注解,然后从注解键和参数值创建一个HashMap。 我的应用程序目前正在使用ParseCloud作为网络库。一个典型的ParseCloud API请求看起来像。
ParseCloud.callFunctionInBackground(String, Map<String, Object>, FunctionCallback<T>)
例如,如果我想执行一个登录请求,我将不得不写(Kotlin)。
fun login(username: String, password: String) {
val params = HashMap<String, Any>()
params["username"] = username
params["password"] = password
val callback = ... //FunctionCallback<LoginResponse>, LoginResponse is response data class
ParseCloud.callFunctionInBackground("apiLogin", params, callback)
如果使用Retrofit,我们可以轻松地写。
@FormUrlEncoded
@POST("apiLogin")
fun login(@Field("username") username: String,
@Field("password") password: String) : Call<LoginResponse>
我喜欢Retrofit API的声明风格,想做同样的东西,所以我开始写。
// Annotation ApiParam, used for variables and parameters
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD, AnnotationTarget.LOCAL_VARIABLE, AnnotationTarget.VALUE_PARAMETER)
annotation class ApiParam(val key: String = "")
// Annotation ApiMethod, used for methods
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class ApiMethod(val api: String)
// Class ApiRequest that holds API path, parameters and method to send request
class ApiRequest<T>(private val api: String, private var params: Map<String, Any>) {
fun send(callback: FunctionCallback<in T>) {
ParseCloud.callFunctionInBackground(api, params, callback)
那么,我应该怎么做才能达到这样的效果。
interface AuthApiService {
@ApiMethod("apiLogin")
fun login(@ApiParam("username") username: String,
@ApiParam("password") password: String): ApiRequest<LoginResponse>
fun login(username: String, password: String) {
val api = ... // Create an instance of interface AuthApiService, it's also a great challenge