【问题标题】:Kotlin - how to get annotation attribute valueKotlin - 如何获取注释属性值
【发布时间】:2016-10-01 11:26:05
【问题描述】:

说,我有一个带注释的 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?
}

【问题讨论】:

    标签: annotations kotlin


    【解决方案1】:

    你可以简单地:

    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
    

    【讨论】:

    • find 等价于firstOrNull,而不是first
    • 是的,在我看来这是暂时的倒退,只是简化了答案,不用担心。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多