Kotlin 反射 Java 方法接受空类数组



我有这样的java代码:

Method m = device.getClass()
        .getMethod("removeBondNative", (Class[]) null);
m.invoke(device, (Object[]) null);

我试图像这样在 Kotlin 中写同样的东西:

device.javaClass.getMethod("removeBondNative", null as Class<*>).invoke(device, null as Any)

但我收到此错误消息:

Process: com.example.zemcd.toofxchange, PID: 17466
   kotlin.TypeCastException: null cannot be cast to non-null type java.lang.Class<*>
       at com.example.zemcd.toofxchange.BluetoothUtils$Companion.unPair(BluetoothUtils.kt:61)
       at com.example.zemcd.toofxchange.DeviceAdapter$DeviceHolder$bindItems$1$$special$$inlined$forEach$lambda$1.onClick(DeviceAdapter.kt:98)
       at android.view.View.performClick(View.java:5217)
       at android.view.View$PerformClick.run(View.java:21349)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5585)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

我还尝试将 null 更改为单位:

device.javaClass.getMethod("removeBondNative", Unit as Class<*>).invoke(device, null as Any)

但仍然遇到错误:

Process: com.example.zemcd.toofxchange, PID: 19219
   java.lang.ClassCastException: kotlin.Unit cannot be cast to java.lang.Class
       at com.example.zemcd.toofxchange.BluetoothUtils$Companion.unPair(BluetoothUtils.kt:61)
       at com.example.zemcd.toofxchange.DeviceAdapter$DeviceHolder$bindItems$1$$special$$inlined$forEach$lambda$1.onClick(DeviceAdapter.kt:98)
       at android.view.View.performClick(View.java:5217)
       at android.view.View$PerformClick.run(View.java:21349)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5585)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

我在这里做错了什么?在这种情况下,Java 反射如何镜像到 Kotlin 中?

错误消息告诉您问题:Class<*> 是非 null 类型,因此强制转换为它始终检查强制转换的值是否为空。你可以写null as Class<*>?,但这相当于(Class) null。你想要null as Array<Class<*>>?

然而,无论如何,这似乎毫无意义:"如果参数类型为空,则将其视为空数组",因此.getMethod("removeBondNative")应该给出相同的结果。

最新更新