Reflection
- Dart course
- Intermediate
- Lesson 80/116
- 5 min
Learn reflection with dart:mirrors.
Reflection with dart:mirrors
Reflection lets a program inspect its own structure at runtime. In Dart the dart:mirrors library provides this. You can see a class's fields, methods and annotations.
For example reflect(obj) gives a mirror of an object; mirror.type reaches its type. This is useful in code generation tools and serialization.
Note: dart:mirrors does not work in Flutter web. It is used in server and CLI apps; it has a high performance cost.
Getting a mirror
To inspect an object first write import 'dart:mirrors';. Then take a mirror with var m = reflect(obj);. m.type gives the type mirror.
From the type mirror m.type.declarations lets you walk the class declarations. Each declaration may be a field, method or constructor.
Reflection is slow and increases size; use it only when truly needed. In most cases compile-time solutions fit better.
Practice Print the type name
Import the reflection library with import 'dart:mirrors';. Define an Item class. In main take a mirror with reflect(Item()) and print m.type.reflectedType with print.
Starter code
// Import the dart:mirrors library
// Define the Item class
void main() {
// print the type of an Item instance
}Sample solution
import 'dart:mirrors';
class Item {}
void main() {
var m = reflect(Item());
print(m.type.reflectedType);
}Expected output
Item
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Importing dart:mirrors
import '____';
void main() {}
import 'dart:mirrors';
void main() {}
Explanation: dart:mirrors is imported for reflection.
2 Where does dart:mirrors not work?
- In CLI apps
- In Flutter web Correct answer
- In server apps
- In console programs
Explanation: dart:mirrors does not work in Flutter web.
3 Reflection parts
| Term | Meaning |
|---|---|
reflect(obj) |
Object mirror |
dart:mirrors |
Reflection library |
m.type |
Type mirror |
declarations |
Declarations |