Why can I use reflection to call private methods of an external class?

Issue

I can use reflection to access and call private methods of a class outside of my library. Is this a bug or desired behaviour? If it’s desired, how can I make it impossible for external code to access private members/methods?

library left;

class Thing {
  void _priv(String s) {
    print(s);
  }
}

library right;

void main() {
  var t = new Thing();
  var mirror = reflect(t);

  mirror.type.declarations.values
  .where( (d) => d.isPrivate && d is MethodMirror )
  .forEach( (d) {
    print(d.simpleName == #_priv); // prints false
    mirror.getField(d.simpleName).reflectee("Hello World"); // prints Hello World
  });
}

Solution

This privacy is not a security feature, is’s only to communicate to users of your API that such a method is intended for internal usage only. Access using mirrors can’t be prevented.

Disallowing it in mirrors wouldn’t prevent access because the VM and dart2js just mangle or prefix private method names to prevent name collisions with public methods. These names can be predicted or found using brute force and then be called.

Answered By – Günter Zöchbauer

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.