You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中访问数据类的字符串成员值?

Kotlin反射获取数据类字符串成员值

原代码与输出

现有可运行的Kotlin代码如下:

data class Abc(
    val a: String,
    val b: String,
    val c: String,
    val d: D
) {
    data class D(
        val e: String,
        val f: String,
        val g: String
    )
}

fun main() {
    val xx = Abc("a1", "b2", "c3", Abc.D("e4", "f5", "g6"))
    xx::class.memberProperties.forEach {
        if (it.returnType.classifier == String::class) {
            println("${it.name} is a String -> ${it.returnType.classifier == String::class} ")
        }
    }
}

运行后输出:

a is a String -> true 
b is a String -> true 
c is a String -> true 

需求

需要修改代码,让输出包含每个字符串成员的具体值,预期输出:

a is a String -> true -> and the value is a1 
b is a String -> true -> and the value is b2 
c is a String -> true -> and the value is c3 

错误尝试

曾尝试以下写法,但无法正常运行:

println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${xx.get(it)}")

正确修改方案

要获取成员属性的值,可利用KProperty1的call()方法(该方法继承自Callable,支持传入任意类型的接收者),或者显式转型后调用get()方法。

方式一:使用call()方法(简洁推荐)

修改后的println语句:

println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${it.call(xx)}")

方式二:显式转型后调用get()

println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${(it as KProperty1<Abc, *>).get(xx)}")

完整修改后的main函数

fun main() {
    val xx = Abc("a1", "b2", "c3", Abc.D("e4", "f5", "g6"))
    xx::class.memberProperties.forEach {
        if (it.returnType.classifier == String::class) {
            println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${it.call(xx)}")
        }
    }
}

运行上述代码即可得到预期的输出。


内容的提问来源于stack exchange,提问作者user3768495

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:03:19