用于java方法的kotlinreflection接受null类数组
我有这样的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)
我在这里做错了什么? 在这种情况下,javareflection如何在Kotlin中镜像?
错误消息告诉你这个问题: Class<*>
是一个非空types,因此总是检查铸造的值是否为空。 你可以写作null as Class<*>?
,但是这相当于(Class) null
。 你想null as Array
代替。
然而,无论如何,这似乎毫无意义: “如果parameterTypes为null,它被视为是一个空数组”,所以.getMethod("removeBondNative")
应该给你相同的结果。