Kotlin:将Array作为vararg参数传递时,参数类型不匹配 [英] Kotlin: Argument Type Mismatch when passing Array as vararg parameter

查看:109
本文介绍了Kotlin:将Array作为vararg参数传递时,参数类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的界面及其实现:

I have a simple interface and its implementation:

interface Iface {
    fun doSomething(s: String)
}

class IfaceImpl : Iface {
    override fun doSomething(s: String) {
        println("Doing the job, s = $s")
    }
}

另外,有两个相同的调用处理程序(至少我不能发现区别),一个在Java中,一个在Kotlin中:

Also, there are two identical (at least I cannot spot the difference) invocation handlers, one in Java and one in Kotlin:

public class JavaHandler implements InvocationHandler {
    private final Iface target;

    public JavaHandler(Iface target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Java handler works");
        return method.invoke(target, args);
    }
}

class KotlinHandler(private val target: Iface) : InvocationHandler {
    override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {
        println("Kotlin proxy works")
        return method!!.invoke(target, args)
    }
}

它们都只输出一些字符串,然后在目标上调用该方法.

They both just output some string and then invoke the method on the target.

最后,这是我运行的代码:

Finally, here is the code I run:

fun main(args: Array<String>) {
    val target = IfaceImpl()
    target.doSomething("one")

    val javaProxy = newProxy(JavaHandler(target))
    javaProxy.doSomething("two")

    val kotlinProxy = newProxy(KotlinHandler(target))
    kotlinProxy.doSomething("three")
}

fun newProxy(handler: InvocationHandler): Iface {
    return Proxy.newProxyInstance(Iface::class.java.classLoader, arrayOf(Iface::class.java), handler) as Iface
}

它使用两个调用处理程序创建两个Java代理,并尝试对其进行练习.

It creates two java proxies, using both invocation handlers, and tries to exercise them.

Java处理程序可以正常工作,但Kotlin处理程序不能正常工作.输出如下:

Java handler works fine, but Kotlin handler does not. The output follows:

Doing the job, s = one
Java handler works
Doing the job, s = two
Kotlin proxy works
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at KotlinHandler.invoke(KotlinHandler.kt:12)
    at com.sun.proxy.$Proxy0.doSomething(Unknown Source)
    at TestKt.main(Test.kt:17)

我可以通过调试器看到,在两种情况下args都包含1个元素,并且是java.lang.Integer实例.

I can see with a debugger that in both cases args consists of 1 element, and it's a java.lang.Integer instance.

有趣的是,如果该方法具有0个参数,则错误消息是不同的:

An interesting thing is that if the method has 0 parameters, the error message is different:

Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

在这种情况下,null作为args参数传递(javadocs允许无参数调用).

In such a case, null is passed as args parameter (which is allowed by javadocs for parameterless calls).

我做错什么了吗?还是这是一个错误?

Do I do something wrong? Or is this a bug?

我的build.gradle具有以下内容:

My build.gradle has the following:

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.2.61'
}

推荐答案

更新:在较新版本的Kotlin中,您可以使用args.orEmpty()代替args ?: emptyArray()

UPDATE: In newer versions of Kotlin you can use args.orEmpty() instead of args ?: emptyArray()

您不能通过args,但需要使用*(args ?: emptyArray()),因为

You cannot pass args but you need to use *(args ?: emptyArray()) because Method.invoke does not expect an array but a variadic parameter.

有关更多信息,请参见此答案

See this answer for more information

我查看了生成的字节码,对于Kotlin,我得到了以下信息:

I looked at the generated bytecode, for Kotlin I get the following:

override fun invoke(proxy : Any?, method : Method, args : Array<Any>?) : Any?
{
    println("Kotlin proxy works")
    return method.invoke(target, args)
}

public java.lang.Object invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]);
Code:
   0: aload_2
   1: ldc           #12                 // String method
   3: invokestatic  #18                 // Method kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull:(Ljava/lang/Object;Ljava/lang/String;)V
   6: ldc           #20                 // String Kotlin proxy works
   8: astore        4
  10: getstatic     #26                 // Field java/lang/System.out:Ljava/io/PrintStream;
  13: aload         4
  15: invokevirtual #32                 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
  18: aload_2
  19: aload_0
  20: getfield      #36                 // Field target:LIface;
  23: iconst_1
  24: anewarray     #4                  // class java/lang/Object
  27: dup
  28: iconst_0
  29: aload_3
  30: aastore
  31: invokevirtual #41                 // Method java/lang/reflect/Method.invoke:(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
  34: areturn

现在,如您所见,Kotlin确实操作了args参数-实际上,它创建了一个新数组. Java不会这样做(它也会跳过null检查):

Now, as you can see, Kotlin does manipulate the args parameter - in fact it creates a new array. Java does not do this (also it skips null-checks):

public Object invoke(Object proxy, Method method, Object args[]) throws Throwable
{
    System.out.println("Java handler works");
    return method.invoke(target, args);
}

public java.lang.Object invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) throws java.lang.Throwable;
Code:
   0: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
   3: ldc           #4                  // String Java handler works
   5: invokevirtual #5                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
   8: aload_2
   9: aload_0
  10: getfield      #2                  // Field target:LIface;
  13: aload_3
  14: invokevirtual #6                  // Method java/lang/reflect/Method.invoke:(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
  17: areturn

现在,让我们截取实际数组.我用Java代码创建了一个充当中介的方法:

Now, let's intercept the actuall array. I created a method in Java code to act as an intermediary:

public static Object invoke0(Iface target, Method method, Object args[]) throws Throwable
{
    System.out.println("Invoking method with " + java.util.Arrays.toString(args));
    return method.invoke(target, args);
}

从Java和Kotlin中执行该操作-并且有效.

Execute that from both Java and Kotlin - and it works.

现在有什么区别?正确,我们希望使用Object[],但

Now what is the difference? Right, we expect an Object[], but Method.invoke takes an Object....

更改中介以采用Object...,我们会收到错误消息以及以下输出:

Change our intermediary to take Object... and we get our error message, along with this output:

Invoking method with [[Ljava.lang.Object;@4b67cf4d]

显然,我们没有传递Object[]而是传递Object[][],这意味着类型不匹配!

So obviously, we aren't passing an Object[] but an Object[][], which means type mismatch!

这篇关于Kotlin:将Array作为vararg参数传递时,参数类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆