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

在Kotlin中如何通过字段名访问对象值?是否有更原生的实现方式?

Kotlin原生实现通过字段名访问对象属性的方案

前置依赖

Kotlin反射能力默认没有打包进标准库,需要先在构建脚本中引入依赖:
Gradle Kotlin DSL写法:

implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlin.coreLibrariesVersion}")

Gradle Groovy写法:

implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

基础实现

对应你给出的示例,Kotlin原生反射的实现代码如下:

import kotlin.reflect.full.declaredMemberProperties

data class Foo(val bar: String)
val foo = Foo("bar")

val barValue = foo::class.declaredMemberProperties
    // 匹配字段名
    .first { it.name == "bar" }
    // 非public属性需要打开访问权限,public属性可省略这行
    .apply { isAccessible = true }
    // 取值
    .get(foo)

println(barValue) // 输出:bar

常用API说明

  • memberProperties:获取当前类+所有父类的public成员属性
  • declaredMemberProperties:仅获取当前类声明的所有属性(包括非public,性能更优)
  • isAccessible = true:Kotlin原生的访问权限开关,替代Java的trySetAccessible()

便捷封装

可以封装为通用扩展函数,全局复用:

import kotlin.reflect.full.declaredMemberProperties

fun Any.getPropertyValue(propertyName: String): Any? {
    return this::class.declaredMemberProperties
        .firstOrNull { it.name == propertyName }
        ?.apply { isAccessible = true }
        ?.get(this)
}

// 调用示例
val barValue = foo.getPropertyValue("bar")

注意事项

  • Kotlin反射库引入后会增加约2.5M的包体积,如果对体积要求极高的场景可以继续使用Java反射方案
  • 反射操作存在固定性能开销,不建议在高频调用的核心链路中使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:15:03