Reflection 对Kotlin中具有默认参数的函数使用callBy时出错
我尝试调用带有默认参数值的函数,而不在Kotlin中放入参数 例如:Reflection 对Kotlin中具有默认参数的函数使用callBy时出错,reflection,kotlin,kotlin-reflect,Reflection,Kotlin,Kotlin Reflect,我尝试调用带有默认参数值的函数,而不在Kotlin中放入参数 例如: class Test { fun callMeWithoutParams(value : Double = 0.5) = value * 0.5 fun callIt(name: String) = this.javaClass.kotlin .members.first { it.name == name } .callBy(emptyMap()) } fu
class Test {
fun callMeWithoutParams(value : Double = 0.5) = value * 0.5
fun callIt(name: String) = this.javaClass.kotlin
.members.first { it.name == name }
.callBy(emptyMap())
}
fun main(args: Array<String>) {
println(Test().callIt("callMeWithoutParams"))
}
奇怪的是,参数不是必需的,而是可选的…从一点测试来看,
KClass
不会跟踪创建它的实际对象,主要区别在于this::class
将使用运行时类型this
您可以通过查询有关所有参数的信息来验证这一点:
name | isOptional | index | kind | type
-----------------------------------------------------
null false 0 INSTANCE Test
value true 1 VALUE kotlin.Double
第一个参数实际上是类的实例。使用this::callMeWithoutParams
将跟踪this
,删除表的第一行,但自然不允许按名称查找成员。您仍然可以通过提供以下对象来调用该方法:
fun callIt(name: String) {
val member = this::class.members.first { it.name == name }
member.callBy(mapOf(member.instanceParameter!! to this))
}
不相关,但
this.javaClass.kotlin
似乎比this::class
有点迂回。
fun callIt(name: String) {
val member = this::class.members.first { it.name == name }
member.callBy(mapOf(member.instanceParameter!! to this))
}