Reputation: 1374
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
});
}
Upvotes: 2
Views: 596
Reputation: 657937
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.
Upvotes: 4
Reputation: 243
Calling private methods are mostly useful in writing the DSL(Domain Specific Language)s.
Upvotes: 0