Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of reflection in Android a bad design?

I am new in Android development. I have a question regarding the usage of Reflection APIs in 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 ?
like image 852
Saby Avatar asked Mar 10 '23 23:03

Saby


1 Answers

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.

like image 152
Hendrik Marx Avatar answered Mar 19 '23 16:03

Hendrik Marx