如何获取 KProperty1 的值
How to get value of KProperty1
I have an object
我尝试访问字段“english”
val englishSentence = dbField::class.declaredMemberProperties.filter { it.name == "english" }[0]
但是当我
model.addAttribute("sentence", englishSentence)
我得到 val com.cyrillihotin.grammartrainer.entity.Sentence.english: kotlin.String
虽然我期望 bla
你是这个意思吗?
data class Sentence(val id:Int, val english:String, val russian:String)
val dbField = Sentence(1, "blaEng", "blaRus")
val englishProp = dbField::class.declaredMemberProperties.first { it.name == "english" }as KProperty1<Sentence, String>
println(englishProp.get(dbField))
它打印blaEng
您可以在 KProperty
上使用 call
函数从对象中获取它的值。
val dbField = Sentence(1, "bla-eng", "bla-rus")
val value = dbField::class.declaredMemberProperties.find { it.name == "english" }!!.call(dbField)
println(value)
输出:bla-eng
记住这里value
的数据类型是Any
。您需要手动将其转换为所需的数据类型。
如果您想列出所有属性及其值,您可以这样做:
dbField::class.declaredMemberProperties.forEach {
println("${it.name} -> ${it.call(dbField)}")
}
输出:
english -> bla-eng
id -> 1
russian -> bla-rus
I have an object
我尝试访问字段“english”
val englishSentence = dbField::class.declaredMemberProperties.filter { it.name == "english" }[0]
但是当我
model.addAttribute("sentence", englishSentence)
我得到 val com.cyrillihotin.grammartrainer.entity.Sentence.english: kotlin.String
虽然我期望 bla
你是这个意思吗?
data class Sentence(val id:Int, val english:String, val russian:String)
val dbField = Sentence(1, "blaEng", "blaRus")
val englishProp = dbField::class.declaredMemberProperties.first { it.name == "english" }as KProperty1<Sentence, String>
println(englishProp.get(dbField))
它打印blaEng
您可以在 KProperty
上使用 call
函数从对象中获取它的值。
val dbField = Sentence(1, "bla-eng", "bla-rus")
val value = dbField::class.declaredMemberProperties.find { it.name == "english" }!!.call(dbField)
println(value)
输出:bla-eng
记住这里value
的数据类型是Any
。您需要手动将其转换为所需的数据类型。
如果您想列出所有属性及其值,您可以这样做:
dbField::class.declaredMemberProperties.forEach {
println("${it.name} -> ${it.call(dbField)}")
}
输出:
english -> bla-eng
id -> 1
russian -> bla-rus