2016-10-01 10 views
5

を取得する方法は、私が注釈で1つの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? 
} 

答えて

7

あなたは、単にすることができます:注釈がRUNTIME保持を有しているので、それがコレクション内Table注釈の実際のインスタンスであるため、

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

注、私はis演算子を使用していました。しかし、任意の注釈のため、次の作品:

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

は 'find'は、うん' firstOrNull'、ない 'first' – Ilya

+0

のと同等である私の心に、それは一時的に後ろ向きだった、ただそれを心配ない答えを簡素化。 –

関連する問題