Saby Saby - 4 years ago 104
Android Question

Usage of reflection in Android a bad design?

I am new to Android development. I have one question regarding the usage of Reflection APIs from Android.

As for example I can write some code like this to connect Bluetooth

try {
Method connectMethod = proxy.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
if(!((Boolean) connectMethod.invoke(proxy, device))){
Log.i(TAG, "Unable to start connection");
} else {
Log.i(TAG, "Connection Successful");
}
} catch (Exception e) {
Log.e(TAG, "Unable to reflect android.bluetooth.BluetoothPan", e);
}


Similarly other APIs can be used to set tethering and do other stuffs.
These functions (like set tethering) are supposed to be done from the Setting application in phone by a user.

These are my questions ?


  1. Is it not recommended to use reflection in android development?

  2. If I create custom permissions for those functions and add to user permissions then is it supported by design ? Because there is no special permission (user permission) required for reflection API access.

  3. As per android design pattern is it a taboo to use reflection APIs ?


Answer Source

Reflection is kind of slow. Although on newer Android versions it is not that bad. The big problem with reflection is that the classes you use might change and you won't notice because the compiler does not know. This is especially bad, when you use it to access third party code that is not under your control or internal apis that are not meant for public consumption. As such it is considered bad practice in general but even more so on Android because of the performance implications. As a rule I would never do anything with reflection that can be done without it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download