Kotlin – 如何获得注释属性值
说,我有一个Kotlin类与注释:
@Entity @Table(name="user") data class User (val id:Long, val name:String)
我怎样才能从@Table注释获得名称属性的值?
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