gpt4 book ai didi

annotations - Kotlin - 如何获取注释属性值

转载 作者:IT老高 更新时间:2023-10-28 13:39:49 27 4
gpt4 key购买 nike

说,我有一个带注释的 Kotlin 类:

@Entity @Table(name="user") data class User (val id:Long, val name:String)

如何从@Table注解中获取name属性的值?

fun <T> tableName(c: KClass<T>):String {
// i can get the @Table annotation like this:
val t = c.annotations.find { it.annotationClass == Table::class }
// but how can i get the value of "name" attribute from t?
}

最佳答案

你可以简单地:

val table = c.annotations.find { it is Table } as? Table
println(table?.name)

注意,我使用了 is 运算符,因为注释具有 RUNTIME 保留,因此它是 Table 注释中的实际实例收藏。但以下适用于任何注释:

val table = c.annotations.find { it.annotationClass == Table::class } as? Table

关于annotations - Kotlin - 如何获取注释属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com