问题描述
我有一个简单的接口及其实现:
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'
}
推荐答案
UPDATE: 在较新版本的 Kotlin 中,您可以使用 args.orEmpty()
而不是 >args ?: emptyArray()
UPDATE: In newer versions of Kotlin you can use args.orEmpty()
instead of args ?: emptyArray()
您不能通过 args
但您需要使用 *(args ?: emptyArray())
因为 Method.invoke
不需要数组而是可变参数.
You cannot pass args
but you need to use *(args ?: emptyArray())
because Method.invoke
does not expect an array but a variadic parameter.
有关详细信息,请参阅此答案
我查看了生成的字节码,对于 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 不这样做(它还跳过空检查):
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[]
,但是 Method.invoke
接受一个 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:将数组作为可变参数传递时参数类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!