调用函数

时间:2018-02-10 19:50:53

标签: reflection kotlin

我试图使用像这样的kotlin原语转换方法将一个未知的给定对象强制转换为所需的类:

private fun callSelfParser(origObj: Any, destClazz: KClass<*>): Any {
        val methodName = when (destClazz) {
            Int::class -> "toInt"
            Char::class -> "toChar"
            Long::class -> "toLong"
            Byte::class -> "toByte"
            Float::class -> "toFloat"
            Short::class -> "toShort"
            Double::class -> "toDouble"
            Boolean::class -> "toBoolean"
            else -> ""
        }

        val parsingMethod: KFunction<*>
        try {
            parsingMethod = origObj::class.functions.toList().first { it ->
                it.name == methodName
            }
        } catch (e: NoSuchElementException) {
            throw ObjectMapperEx("Element $origObj doesn't have a method for parsing to $destClazz")
        }

        return parsingMethod.call(origObj)!!
    }

但是在执行.call()时出现以下异常:

Exception in thread "main" kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Reflection on built-in Kotlin types is not yet fully supported. No metadata found for public open val length: kotlin.Int defined in kotlin.String[DeserializedPropertyDescriptor@1cbb87f3]

有人可以说什么是错的,或者,如果还有另一种方法来实现我的目标?

0 个答案:

没有答案