CodeBlanks Logo Icon CodeBlanks

Mirror

Learn InstanceMirror and ClassMirror.

InstanceMirror and ClassMirror

In dart:mirrors, reflect(obj) returns an InstanceMirror. Through this mirror you access the object's fields and methods.

reflectClass(T) returns a ClassMirror. A ClassMirror lets you list the class's fields, methods and supertypes.

Example: var m = reflect(u); print(m.type.simpleName);. simpleName is a Symbol; convert it to text with MirrorSystem.getName(sym).

Symbol and getName

In the Mirror API, names are represented as Symbols. They are created with Symbol('name') or the #name literal.

To convert a Symbol to text, call MirrorSystem.getName(symbol). Example: MirrorSystem.getName(#hello) → 'hello'.

Symbols survive minification; therefore fields accessed via reflection are kept as Symbols.

Practice Inspect class fields via runtimeType

Define class Point { double x; double y; Point(this.x, this.y); }. Inside main create var p = Point(3.0, 4.0);; add print(p.runtimeType); and print(p.x);.

Starter code

main.dart
void main() {
  // define the Point class (outside main)
  // create an instance; print runtimeType and x
}

Sample solution

main.dart
class Point {
  double x;
  double y;
  Point(this.x, this.y);
}

void main() {
  var p = Point(3.0, 4.0);
  print(p.runtimeType);
  print(p.x);
}

Expected output

Point
3.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Reflect an object

Question
var m = ____(u);
Answer
var m = reflect(u);

Explanation: reflect(u) returns an InstanceMirror.

2 What does reflectClass return?

  • Symbol
  • InstanceMirror
  • Type
  • ClassMirror Correct answer

Explanation: reflectClass returns a ClassMirror.

3 Match mirror concepts

Term Meaning
reflect(obj) InstanceMirror
reflectClass(T) ClassMirror
Symbol Name abstraction
getName To-text conversion

All lessons in Advanced