dimanche 2 août 2020

Dynamically (at Runtime) Calling The iterator Operator Function Of An Array

When attempting to dynamically (reflection) call the iterator function of an array type

    @Test
    fun test_x() {
        val array: Array<String> = arrayOf("A", "B")
        val f: KFunction<*> = array::class.memberFunctions.filter { it.name == "iterator" && it.isOperator }.first()
        KotlinReflectionUtils.functionJsonInfo(f).printJson()
        val result = f.call(array)
        println(result)
    }

KotlinReflectionUtils.functionJsonInfo(f).printJson() is a debug line with the following output

{
    "name" : "iterator",
    "returnType" : "kotlin.collections.Iterator<T>",
    "parameters" : [ {
        "index" : 0,
        "name" : null,
        "type" : {
            "toString()" : "kotlin.Array<T>",
            "classifier" : "class kotlin.Array"
        },
        "java_class" : "kotlin.reflect.jvm.internal.KParameterImpl",
        "optional?" : false,
        "vararg?" : false,
        "isValue?" : false
    } ],
    "instance_receiver_parameter" : {
        "index" : 0,
        "name" : null,
        "type" : {
            "toString()" : "kotlin.Array<T>",
            "classifier" : "class kotlin.Array"
        },
        "java_class" : "kotlin.reflect.jvm.internal.KParameterImpl",
        "optional?" : false,
        "vararg?" : false
    },
    "visibility" : "public",
    "external?" : false,
    "infix?" : false,
    "inline?" : false,
    "operator?" : true,
    "isFinal?" : true,
    "suspend?" : false
}

val result = f.call(array) throws the following exception

kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Could not compute caller for function: public final operator fun iterator(): kotlin.collections.Iterator defined in kotlin.Array[DeserializedSimpleFunctionDescriptor@1199fe66] (member = null)





Aucun commentaire:

Enregistrer un commentaire