gpt4 book ai didi

java - java方法接受null类数组的kotlin反射

转载 作者:行者123 更新时间:2023-12-02 12:07:54 24 4
gpt4 key购买 nike

我有这样的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 更改为 Unit:

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 as Class<*>? ,但这相当于 (Class) null 。您想要null as Array<Class<*>>?相反。

但是,无论如何,这似乎毫无意义:"If parameterTypes is null, it is treated as if it were an empty array"所以.getMethod("removeBondNative")应该给你相同的结果。

关于java - java方法接受null类数组的kotlin反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46759959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com