Is it possible to use Kotlin reflection from Java?
I want to get KCallable
from Kotlin function in Java and use its method callBy
to call method with default arguments.
Example in Kotlin:
fun test(a: String = "default", b: String): String {
return "A: $a - B: $b";
}
fun main() {
val callable: KCallable<*> = ::test
val parameterB = callable.parameters[1]
val result = callable.callBy(mapOf(
parameterB to "test"
))
println(result)
}
Is it even possible? If so, how to get instance of KCallable
from Java code?
EDIT:
I cannot use @JvmOverloads
as suggested, because the number of arguments, default arguments and their positions can be arbitrary.
The known information for calling is:
- names of arguments
- their type
- their value
EDIT 2:
Example of not working @JvmOverloads
here:
fun test(a: String = "default", b: String = "default"): String {
return "A: $a - B: $b";
}
Here calling with one String
value is ambiguous.