Kotlin 反射应用到解析,一个例子

问题描述 投票:0回答:1

我正在试验Kotlin的反射机制。但是,当我尝试递归应用该函数时,出现了问题。我学习 Kotlin 还不到一个月,完全超出了我的能力范围。请指导我?

import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.findAnnotation

annotation class CsByte
annotation class CsStruct

class Struct1 {
    @CsByte
    var x: Int = 0
    @CsStruct
    var inner1: Inner = Inner()
}

class Inner {
    @CsByte
    var y: Int = 0
}

fun <T : Any> parseStructRecursively (type:KClass<T>): T {
    val obj = type.constructors.find { it.parameters.isEmpty() }?.call()!!
    for (field in type.members) {
        if (field.findAnnotation<CsByte>() != null)
            (field as KMutableProperty<*>).setter.call(obj, 9)
        if (field.findAnnotation<CsStruct>() != null)
            (field as KMutableProperty<*>).setter.call(obj, parseStructRecursively(field::class))
            //                                                                     ^^^^^^^^^^^^ wrong?
            // Inner::class works OK,  field::class fails because it does not have argumentless constructor.
    }
    return obj
}

inline fun <reified T : Any> parseReified (): T {
    return parseStructRecursively(T::class)
}

fun main() {
    var s1 = parseReified<Struct1>()
    println(s1.x == 9)
    println(s1.inner1.y == 9)
}
kotlin class recursion reflection
1个回答
0
投票

事实证明,我纯粹是偶然发现的,

Inner::class
可以使用
field.getter.returnType.jvmErasure
找到。谁知道?

© www.soinside.com 2019 - 2024. All rights reserved.