What is the difference between Mirror based reflection and traditional reflection?

Issue

Some languages like Dart use mirror based reflection so, in simple terms, what is the difference between such implementation and traditional reflection as you see in C# or Java.

Update:
I found this excellent (and somewhat quirky) video by Gilad Bracha on Mirror based reflection in Newspeak.
http://www.hpi.uni-potsdam.de/hirschfeld/events/past/media/100105_Bracha_2010_LinguisticReflectionViaMirrors_HPI.mp4 (mirror stuff starts at 7:42)

Solution

For many uses, I don’t think mirrors will be that different than Java reflection. The most important thing understand about mirrors is that they decouple the reflection API from the standard object API, so instead of obj.getClass() you use reflect(obj). It’s a seemingly small difference, but it gives you a few nice things:

  1. The object API isn’t polluted, and there’s no danger of breaking reflection by overriding a reflective method.
  2. You can potentially have different mirror systems. Say, one that doesn’t allow access to private methods. This could end up being very useful for tools.
  3. The mirror system doesn’t have to be included. For compiling to JS this can be important. If mirrors aren’t used then there’s no out-of-band to access code and pruning becomes viable.
  4. Mirrors can be made to work on remote code, not just local code, since you don’t need the reflected object to be in the same Isolate or VM as the mirror.

Here’s how mirrors are different than reflection in Java and Javascript when used to get an object’s methods:

Java:

myObject.getClass().getMethods(); // returns an array

Dart:

reflect(myObject).type.methods; // returns a map

Javascript:

var methods = [];
for (var m in myObject) {
  if (typeof m === 'function') {
    methods.push(m);
  }
}

Answered By – Justin Fagnani

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.