我想创建自定义请求解析器,我想通过注释字段并通过反射来获取值,但是我只能从类字段中获取注释,下面的代码不适用于数据类或类中的构造函数,你知道哪里有问题吗?
open class RequestParser {
fun getRequestWithTag(): String {
var requestString = "<RequestData>"
val declaredMemberProperties = this::class.declaredMemberProperties
declaredMemberProperties.filter {
it.findAnnotation<RequestField>() != null
}.forEach { filteredMemberProperties ->
requestString += "<${filteredMemberProperties.name.firstLetterToUpperCase()}>${filteredMemberProperties.getter.call(this)}</${filteredMemberProperties.name.firstLetterToUpperCase()}>"
}
requestString += "</RequestData>"
return requestString
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(
FIELD,
PROPERTY,
PROPERTY_GETTER,
VALUE_PARAMETER,
PROPERTY_SETTER,
CONSTRUCTOR,
FUNCTION)
public annotation class RequestField
//model example
data class RequestTest(
@RequestField val name: String
) : RequestParser()
//using example
RequestTest("name").getRequestWithTag()
答案 0 :(得分:0)
数据类构造函数中的属性有很多,构造函数参数,getter,setter和字段。因此,您需要设置使用场所目标来表达您的实际意思。
class Example(@field:Ann val foo, // annotate Java field
@get:Ann val bar, // annotate Java getter
@param:Ann val quux) // annotate Java constructor parameter
另请参阅https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets
因此,在您的情况下,我将尝试以下操作:
data class RequestTest(
@property:RequestField val name: String
) : RequestParser()
借助property
,我可以从this::class.declaredMemberProperties
处获取注释
如果您放置field
,则可以通过this::class.java.declaredFields