vendredi 21 mai 2021

Get private method with reflection in order to pass it to a higher order function in Kotlin

I'm having a hard time trying to get a private method in Kotlin using reflection in order to pass it as a parameter to a higher order function, here is what I got and what I need to do:

The function that gets the private method, probably what I should change or fix:

inline fun <reified T> T.getPrivateFunc(name: String): KFunction<*> {
    return T::class.declaredMemberFunctions.first { 
        it.name == name 
    }.apply { 
        isAccessible = true 
    }
}

This is the high order function I have:

class MyService {

    fun myHigherOrderFunction(action: () -> Unit) { /*...*/ }
}

These are the class and the private method I need to get somehow:

class SystemUnderTest {

    fun privateFunc() { /*...*/ }
}

Finally a unit test where I I'm trying to make sure the proper method is passed to the high order function, I omitted details for simplification:

// ...
val serviceMock = MyService()
val sut = SystemUnderTest()
// Here is what I'm trying to accomplish
val privateMethod = sut.getPrivateMethod("privateFunc")
service.myHighOrderFunction(privateMethod) 
// In the above line I get a compilation error: required () - Unit, found KFunction<*>
service.myHigherOrderFunction(privateMethod as () -> Unit) 
// In the above line I get the following runtime error:
// ClassCastException: kotlin.reflect.jvm.internal.KFunctionImpl cannot be cast to kotlin.jvm.functions.Function1

I know the test can be done having the privateFunc as public and maybe annotating it with @VisibleForTesting, but what I want is to avoid compromising the design as long as I can.

Any ideas? Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire