CodeBlanks Logo Icon CodeBlanks

Reflection

Learn reflection with dart:mirrors.

What is reflection?

Reflection is a program inspecting its own structure at runtime: class names, fields, methods, annotations. In Dart the dart:mirrors library provides it.

Typical uses: serialization (JSON ↔ object), dependency injection, test mocks. But dart:mirrors is not supported in Flutter/AOT; most projects therefore prefer code generation (source_gen).

The simplest reflection tool is runtimeType: every object knows its type. obj.runtimeType returns the corresponding Type object.

Type info via runtimeType

Every Dart object has a runtimeType property. It returns the object's dynamic type and does not require mirrors — it works everywhere.

Example: var u = User('Ayşe'); print(u.runtimeType); prints User. This is the simplest form of reflection.

Deeper inspection (listing fields, dynamic method invocation) requires dart:mirrors; but runtimeType suffices for most debug and logging needs.

Practice Print the type with runtimeType

Define class User { String name; User(this.name); }. Inside main create var u = User('Ayşe'); and add print(u.runtimeType);.

Starter code

main.dart
void main() {
  // define the User class (outside main)
  // create an instance and print its type name
}

Sample solution

main.dart
class User {
  String name;
  User(this.name);
}

void main() {
  var u = User('Ayşe');
  print(u.runtimeType);
}

Expected output

User

Questions and answers

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

1 Where is dart:mirrors unsupported?

  • Dart VM (console)
  • Only web
  • Flutter / AOT compilation Correct answer
  • Test environment

Explanation: dart:mirrors does not work in Flutter and AOT compilation.

2 Get type info

Question
print(u.____);
Answer
print(u.runtimeType);

Explanation: runtimeType gives the object's dynamic type.

3 Match reflection tools

Term Meaning
dart:mirrors Full reflection
runtimeType Basic type info
source_gen Code generation
annotation Metadata

All lessons in Advanced