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: