vendredi 7 octobre 2022

How to call a private class's static function using Kotlin's reflection?

I know how to invoke it in Java's reflection and it works like a charm, but I can't seem to get it to work using Kotlin's reflection.

Sample code:

    fun main() {
        // using Java reflection
        val clazz = AccessAHiddenClass::class.java
        val method = clazz.getMethod("someStaticFunction", String::class.java, Int::class.java)
        val result = method.invoke(null, "Java", 27) as String
        println(result)

        // using Kotlin reflection
        val klass = AccessAHiddenClass::class
        klass.memberFunctions.find {
            it.name == "someStaticFunction"
        }?.let {
            val kotlinResult = it.call( null, "Kotlin", 6)
            println(kotlinResult)
        }
    }

    private class AccessAHiddenClass {
        companion object {
            @JvmStatic
            fun someStaticFunction(name: String, age: Int) = "my name is $name, I'm $age years old"
        }
    }

After messing around I managed to write the following Kotlin reflection code, but only after removing the private visibility modifier from AccessHiddenClass class.

val klass = AccessAHiddenClass::class.companionObject
val kompanionObject = AccessAHiddenClass::class.companionObjectInstance
klass?.functions?.find {
    it.name == "someStaticFunction"
}?.let {
    val kResult = it.call(kompanionObject, "Test", 10)
    println(kResult)
}

Is there a way to modify AccessAHiddenClass's class visibility reflectively?





Aucun commentaire:

Enregistrer un commentaire