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