samedi 10 février 2018

Kotlin reflection error when calling function

I was trying to cast an unknown given object to the required class using kotlin primitives conversion methods like this:

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 = destClazz.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)!!
    }

But I got the following exception when executing the .call():

kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Call is not yet supported for this function: public open fun toInt(): kotlin.Int defined in kotlin.Int[DeserializedSimpleFunctionDescriptor@25bc0606] (member = null)

Can someone say whats wrong or, if there's another way to achieve my goal?





Aucun commentaire:

Enregistrer un commentaire