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

如何在Kotlin中用另一个对象填充当前实例(this)

Kotlin 实现对象属性复制到当前实例(反射方式)

要实现将另一个对象的所有属性复制到当前对象实例(this),object.copy() 无法满足需求(它会创建新实例而非修改当前实例),可以通过Kotlin反射实现类似你提供的C#功能,具体代码如下:

实现代码

fun Any.fillFromObject(obj: Any) {
    val targetClass = this::class
    val sourceClass = obj::class

    // 遍历当前对象的所有可写属性
    targetClass.memberProperties.filterIsInstance<KMutableProperty<*>>().forEach { targetProp ->
        // 从源对象中查找同名属性
        val sourceProp = sourceClass.memberProperties.find { it.name == targetProp.name }
        sourceProp?.let {
            // 校验源属性可读且类型兼容
            if (it is KProperty<*> && targetProp.returnType.isSupertypeOf(it.returnType)) {
                try {
                    targetProp.setter.call(this, it.get(obj))
                } catch (e: Exception) {
                    // 可根据业务需求调整异常处理逻辑
                    e.printStackTrace()
                }
            }
        }
    }
}

使用方式

this.fillFromObject(anotherObject)

注意事项

  • 若为JVM项目,需添加kotlin-reflect依赖到构建脚本(以Gradle为例):
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}"
}
  • 函数会自动跳过不可写的属性,以及源对象中不存在的同名属性;若属性类型不兼容,会捕获异常并打印堆栈信息,可根据实际需求修改异常处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:32:07