mardi 2 octobre 2018

Refactor method which uses reflection from Java to Kotlin

I am trying to convert Java method which checks the SignalStrength level for Android API's which is like this:

public static int getSignalLevel(final SignalStrength signal) {
try {
    final Method m = SignalStrength.class.getDeclaredMethod("getLevel", (Class[]) null);
    m.setAccessible(true);
    return (Integer) m.invoke(signal, (Object[]) null);
} catch (Exception e) {
    Log.debug(TAG, "Google hates developers", e);
    return 0;
  }
}

When converted to Kotlin I am getting this (I aim to make Kotlin Extension):

fun SignalStrength.getSignalLevel(): Int {
return try {
val m = SignalStrength::class.java.getDeclaredMethod("getLevel", *null as Array<Class<*>>?)
m.isAccessible = true
m.invoke(this, *null as Array<Any>?) as Int
} catch (e: Exception) {
0
}

}

The issue is for:

*null as Array<Class<*>>?

The spread operator (*foo) may not be applied to an argument of nullable type





Aucun commentaire:

Enregistrer un commentaire