Question

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)

Was it helpful?

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);
  }
}

OTHER TIPS

Your best bet is this article by Gilad Bracha, Dart's co-designer and specification author. To get a glimpse, it will probably be enough to read the first chapter.

The abstract claims that mirrors adhere to three necessary principles that aren't followed by traditional reflection:

We identify three design principles for reflection and metaprogramming facilities in object oriented programming languages. Encapsulation: meta-level facilities must encapsulate their implementation. Stratification: meta-level facilities must be separated from base-level functionality. Ontological correspondence: the ontology of meta-level facilities should correspond to the ontology of the language they manipulate. Traditional/mainstream reflective architectures do not follow these precepts. In contrast, reflective APIs built around the concept of mirrors are characterized by adherence to these three principles.

I would also point you to this other recent answer by Gilad, where he lists some other great reference material: How to get concrete object of a static method via mirror API?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top