假設你只有1層構造,在這裏你去:
inline fun <reified D> convert(c: Any) : D {
val list = mutableListOf<Any>()
c::class.java.declaredFields.forEach {
it.isAccessible = true
list.add(it.get(c) as String)
it.isAccessible = false
}
val constructor = D::class.java.declaredConstructors[0]
return constructor.newInstance(*list.toTypedArray()) as D
}
充分利用:
package com.erezbiox1
fun main(args: Array<String>){
val A = A("Hey", "Hello")
val B = convert<B>(A)
B.print()
}
inline fun <reified D> convert(c: Any) : D {
val list = mutableListOf<Any>()
c::class.java.declaredFields.forEach {
it.isAccessible = true
list.add(it.get(c) as String)
it.isAccessible = false
}
val constructor = D::class.java.declaredConstructors[0]
return constructor.newInstance(*list.toTypedArray()) as D
}
class A(val a: String, val b: String){
fun print(){
println("Value is: $a, $b")
}
}
class B(val a: String, val b: String) {
fun print(){
println("Value is: $a, $b")
}
}
這尖叫「在繼承組成」 .. –
你必須提供它在你的構造函數並手動分配每個字段。 – tynn
如果您可以從Java庫切換到Kotlin數據類,您將獲得內置的複製方法。 – Les