我知道如何在Kotlin中反映和迭代单个对象的属性,以查找特定类型的所有属性:
object Obj1{
val obj1Int = 1
val obj1String = "one"
}
fun main(){
// filter out the integer property, keep the string property
Obj1::class
.declaredMemberProperties
.mapNotNull { it.get(Obj1) as? String }
.forEach { println(it) } // prints "one", does not print "1"
}
但当我有一个通用对象列表时,我很难让它工作:
object Obj1{
val obj1Int = 1
val obj1String = "one"
}
object Obj2{
val obj2Int = 2
val obj2String = "two"
}
fun main() {
listOf(Obj1, Obj2).forEach {obj ->
obj::class.declaredMemberProperties
.mapNotNull { it.get(obj) as? String } // compiler error
.forEach { println(it) }
}
}
it.get(obj)
有错误:Type mismatch: inferred type is Any but Nothing was expected
我该怎么做?