So I want to call coroutines/suspend functions via reflection. I hacked around until I got something working, see below. Can anyone confirm that this is the proper way to call suspend functions via reflection?
class FieldGetterCoroutine(
private val callable: KCallable<*>,
private val params: Array<ParamInfo>
) {
suspend fun invoke(receiver: Any): Any? {
return suspendCoroutineOrReturn { cont ->
val args = arrayOfNulls<Any?>(params.size)
for (i in params.indices) {
val param = params[i]
args[i] = when (param.kind) {
ParamKind.THIS -> receiver
ParamKind.CONTINUATION -> cont
else -> /* some other cases, not that relevant */
}
}
try {
return@suspendCoroutineOrReturn callable.call(*args)
} catch (e: InvocationTargetException) {
throw e.targetException
}
}
}
}