Kotlin data class: how to read the value of property if I don't know its name at compile time?

前端 未结 4 1388
南方客
南方客 2020-12-03 04:53

How can I read the value of property in a Kotlin data class instance if the property name is only known at runtime?

4条回答
  •  广开言路
    2020-12-03 05:31

    Here is a function to read a property from an instance of a class given the property name (throws exception if property not found, but you can change that behaviour):

    import kotlin.reflect.KProperty1
    import kotlin.reflect.full.memberProperties
    
    @Suppress("UNCHECKED_CAST")
    fun  readInstanceProperty(instance: Any, propertyName: String): R {
        val property = instance::class.members
                         // don't cast here to , it would succeed silently 
                         .first { it.name == propertyName } as KProperty1 
        // force a invalid cast exception if incorrect type here
        return property.get(instance) as R  
    }
    

    build.gradle.kts

    dependencies {
        implementation(kotlin("reflect"))
    }
    

    Using

    // some data class
    data class MyData(val name: String, val age: Int)
    val sample = MyData("Fred", 33)
    
    // and reading property "name" from an instance...
    val name: String = readInstanceProperty(sample, "name")
    
    // and reading property "age" placing the type on the function call...
    val age = readInstanceProperty(sample, "age")
    
    println(name) // Fred
    println(age)  // 33
    

提交回复
热议问题