Kotlin - 如何获取注释属性值

时间:2016-10-01 11:26:06

标签: annotations kotlin

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

1 个答案:

答案 0 :(得分:10)

你可以简单地说:

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