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

时间:2017-10-15 21:01:35

标签: java android reflection kotlin

我有这样的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)

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

1 个答案:

答案 0 :(得分:1)

错误消息告诉您问题:Class<*>是非null类型,因此强制转换它总是检查转换值是否为null。您可以写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")应该给你相同的结果。