Home > Enterprise >  Kotlin: IllegalArgumentException while trying to call function of other classes by reflection
Kotlin: IllegalArgumentException while trying to call function of other classes by reflection

Time:06-08

I try to call methods by reflection in kotlin and it doesn't work.

My code (simplyfied, null-checks and catch-exceptions omitted):

class MyCallerClass() {

  val allCallableMethods: List<KFunction<Unit>> = ... 

  // request: we're within a web-page. The user can see the callable methods and click which one to call 
  fun handleRequest(request: HttpServletRequest) {

    val callableMethodName = request.getParameter(callableMethodNameParam)
    if (callableMethodName != null) {
      for (method in allCallableMethods) {
        if (method.name == callableMethodName) {
          // we found the method the user wants to call!

          val paramMap: MutableMap<KParameter, Any> = mutableMapOf()
            
          // this part I added after I got an IllegalArgumentException. See below
          if (method is CallableReference) {
            paramMap[method.instanceParameter!!] = method.owner
          }

          for (param in method.valueParameters) {
            val paramName = if (param.name != null) {
              param.name!!
            }

            val paramValue: String? = request.getParameter(paramName)
            if(paramValue != null) {
              paramMap[param] = paramValue
            }
          }

          method.callBy(paramMap)
        }
      }
    }
  }
}

So first I only collected all params in the paramMap, but that resulted in "java.lang.IllegalArgumentException: No argument provided for a required parameter: instance parameter of fun...".

Luckily I found questions here that helped me on:

  • enter image description here. There are multiple possabilities. One i can think of:

    • When running within a suspend function, IDEA sometimes skips executions when they will be executed in another coroutine scope

    Maybe this is a kickstart to your questions. Please reply if one of your question is not answered.

  • Related