import kotlin.reflect.KClass
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
/**
* Created by FangJu on 2020/1/31
*/
data class Group(val id: Int, val name: String, val location: String)
data class Person(val id: Int, val name: String, val group: Group)
fun <T : Any> T.deepCopy(): T {
if (!this::class.isData) {//不是数据类直接返回
return this
}
return this::class.primaryConstructor!!.let { primaryConstructor ->
primaryConstructor.parameters.map { kParameter ->
val value = (this::class as KClass<T>).memberProperties.first {
it.name == kParameter.name
}.get(this)
if ((kParameter.type.classifier as? KClass<*>)?.isData == true) {
kParameter to value?.deepCopy()
} else {
kParameter to value
}
}.toMap()
.let(primaryConstructor::callBy)
}
}
fun main() {
val group = Group(1, "group", "hb")
val person = Person(2, "person", group)
val cloneGroup = group.copy()
val deepCloneGroup = group.deepCopy()
println("cloneGroup === group : ${cloneGroup === group}") //false
println("deepCloneGroup === group : ${deepCloneGroup === group}") //false
val clonePerson = person.copy()
val deepClonePerson = person.deepCopy()
println("person.group === clonePerson.group : ${person.group === clonePerson.group}") //true
println("person.group === deepClonePerson.group : ${person.group === deepClonePerson.group}") //false
}
为数据类实现DeepCopy
最新推荐文章于 2024-05-25 09:50:28 发布