Reflection java.lang.IllegalArgumentException:Callable需要4个参数,但提供了3个
我试图使用Kotlin反射调用函数,但出现错误: java.lang.IllegalArgumentException:Callable需要4个参数,但是 提供了3个 这是执行反射调用的代码:Reflection java.lang.IllegalArgumentException:Callable需要4个参数,但提供了3个,reflection,kotlin,Reflection,Kotlin,我试图使用Kotlin反射调用函数,但出现错误: java.lang.IllegalArgumentException:Callable需要4个参数,但是 提供了3个 这是执行反射调用的代码: annotation.listeners.forEach { listener: KClass<*> -> listener.functions.forEach { function: KFunction<*> -> if
annotation.listeners.forEach { listener: KClass<*> ->
listener.functions.forEach { function: KFunction<*> ->
if (function.name == "before") {
function.call(annotation.action, request, response)
}
}
}
为了再次检查我的类型是否正确,我执行了以下操作:
if (function.name == "before") {
println(annotation.action::class)
println(request::class)
println(response::class)
}
这将打印(这是before
功能所需的正确类型):
第四个参数应该是什么?缺少“this”参数,该参数是应该调用方法的对象
它应该是该方法的第一个参数它不是直接显而易见的,但让我们看看以下文档: “如果参数的数量不等于[parameters][…]的大小,则引发异常。”。另一方面,参数是带有以下文档的
列表
:
/**
* Parameters required to make a call to this callable.
* If this callable requires a `this` instance or an extension receiver parameter,
* they come first in the list in that order.
*/
public val parameters: List<KParameter>
打印的参数
如下所示:
fun de.swirtz.jugcdemo.prepared.X.before的实例(kotlin.String、kotlin.String、kotlin.String):kotlin.Unit
参数#1 fun de.swirtz.jugcdemo.prepared.X.before(kotlin.String、kotlin.String、kotlin.String)的操作:kotlin.Unit
参数#2 fun de.swirtz.jugcdemo.prepared.X.before的请求(kotlin.String、kotlin.String、kotlin.String):kotlin.Unit
参数#3 fun de.swirtz.jugcdemo.prepared.X.before(kotlin.String、kotlin.String、kotlin.String)的响应:kotlin.Unit
啊,是的,它显然需要一个实例来调用它。我在检查
call
方法时看到了这一点,因此我打印问题中的类型以确认我的类型是正确的。您在哪里找到第二个注释块?如果第一个注释块提到第一个参数应该是实例,那就太好了,尽管如果您以前做过,这可能很明显。它都在KCallable
:)啊,对了,用指定的调用这个可调用的,这个
实际上引用了实例,当我在源代码和评论块的复制粘贴中读到这句话时,我对它的理解有些不同。第二个评论块马上就显而易见了。
class kotlin.String
class com.mycompany.RestRequest
class com.mycompany.RestResponse
/**
* Calls this callable with the specified list of arguments and returns the result.
* Throws an exception if the number of specified arguments is not equal to the size of [parameters],
* or if their types do not match the types of the parameters
*/
public fun call(vararg args: Any?): R
/**
* Parameters required to make a call to this callable.
* If this callable requires a `this` instance or an extension receiver parameter,
* they come first in the list in that order.
*/
public val parameters: List<KParameter>
class X{
fun before(action: String, request: String, response: String)= println("called")
}
fun main(args: Array<String>) {
X::class.functions.forEach { function: KFunction<*> ->
if (function.name == "before") {
function.parameters.forEach{ println(it)}
//function.call(X(), "a", "b", "c")
}
}
}