update: updating documents
This commit is contained in:
parent
44fb7ab881
commit
8c2b018c3d
8 changed files with 535 additions and 1568 deletions
|
@ -1,169 +1,47 @@
|
||||||
# Platform Reflection
|
# Platform Reflection
|
||||||
|
|
||||||
A powerful cross-platform reflection system for Dart that provides runtime type introspection and manipulation. This implementation offers a carefully balanced approach between functionality and performance, providing reflection capabilities without the limitations of `dart:mirrors`.
|
A powerful cross-platform reflection system for Dart that serves as a drop-in replacement for `dart:mirrors`. This implementation offers a carefully balanced approach between functionality and performance, providing reflection capabilities with AOT compilation support.
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
|
|
||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Architecture](#architecture)
|
|
||||||
- [Installation](#installation)
|
- [Installation](#installation)
|
||||||
- [Core Components](#core-components)
|
- [Usage](#usage)
|
||||||
- [Usage Guide](#usage-guide)
|
|
||||||
- [Advanced Usage](#advanced-usage)
|
|
||||||
- [Performance Considerations](#performance-considerations)
|
|
||||||
- [Migration Guide](#migration-guide)
|
|
||||||
- [API Reference](#api-reference)
|
- [API Reference](#api-reference)
|
||||||
|
- [Performance Considerations](#performance-considerations)
|
||||||
- [Limitations](#limitations)
|
- [Limitations](#limitations)
|
||||||
|
- [Migration from dart:mirrors](#migration-from-dartmirrors)
|
||||||
- [Contributing](#contributing)
|
- [Contributing](#contributing)
|
||||||
- [License](#license)
|
- [License](#license)
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### Core Features
|
|
||||||
- ✅ Platform independent reflection system
|
- ✅ Platform independent reflection system
|
||||||
|
- ✅ AOT compilation support
|
||||||
- ✅ No dependency on `dart:mirrors`
|
- ✅ No dependency on `dart:mirrors`
|
||||||
- ✅ Pure runtime reflection
|
|
||||||
- ✅ Library scanning and reflection
|
|
||||||
- ✅ Explicit registration for performance
|
|
||||||
- ✅ Type-safe operations
|
|
||||||
- ✅ Comprehensive error handling
|
|
||||||
|
|
||||||
### Reflection Capabilities
|
|
||||||
- ✅ Class reflection with inheritance
|
- ✅ Class reflection with inheritance
|
||||||
- ✅ Method invocation with named parameters
|
- ✅ Method invocation with named parameters
|
||||||
- ✅ Property access/mutation
|
- ✅ Property access and mutation
|
||||||
- ✅ Constructor resolution and invocation
|
- ✅ Constructor resolution and invocation
|
||||||
- ✅ Type introspection and relationships
|
- ✅ Type introspection and relationships
|
||||||
- ✅ Library dependency tracking
|
- ✅ Explicit registration for performance
|
||||||
- ✅ Parameter inspection and validation
|
- ✅ Basic generic type support
|
||||||
- ✅ Top-level variable support
|
- ✅ Comprehensive error handling
|
||||||
|
|
||||||
### Performance Features
|
|
||||||
- ✅ Cached class mirrors
|
|
||||||
- ✅ Optimized type compatibility checking
|
|
||||||
- ✅ Efficient parameter resolution
|
|
||||||
- ✅ Smart library scanning
|
|
||||||
- ✅ Memory-efficient design
|
|
||||||
- ✅ Lazy initialization support
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Core Components
|
|
||||||
|
|
||||||
```
|
|
||||||
platform_reflection/
|
|
||||||
├── core/
|
|
||||||
│ ├── library_scanner.dart # Library scanning and analysis
|
|
||||||
│ ├── reflector.dart # Central reflection registry
|
|
||||||
│ ├── runtime_reflector.dart # Runtime reflection implementation
|
|
||||||
│ └── scanner.dart # Type scanning and analysis
|
|
||||||
├── mirrors/
|
|
||||||
│ ├── base_mirror.dart # Base mirror implementations
|
|
||||||
│ ├── class_mirror_impl.dart # Class reflection
|
|
||||||
│ ├── instance_mirror_impl.dart # Instance reflection
|
|
||||||
│ ├── library_mirror_impl.dart # Library reflection
|
|
||||||
│ ├── method_mirror_impl.dart # Method reflection
|
|
||||||
│ └── ... (other mirrors)
|
|
||||||
├── annotations.dart # Reflection annotations
|
|
||||||
├── exceptions.dart # Error handling
|
|
||||||
├── metadata.dart # Metadata definitions
|
|
||||||
└── types.dart # Special type implementations
|
|
||||||
```
|
|
||||||
|
|
||||||
### Design Principles
|
|
||||||
|
|
||||||
1. **Explicit Registration**
|
|
||||||
- Clear registration of reflectable types
|
|
||||||
- Controlled reflection surface
|
|
||||||
- Optimized runtime performance
|
|
||||||
|
|
||||||
2. **Type Safety**
|
|
||||||
- Strong type checking
|
|
||||||
- Compile-time validations
|
|
||||||
- Runtime type verification
|
|
||||||
|
|
||||||
3. **Performance First**
|
|
||||||
- Minimal runtime overhead
|
|
||||||
- Efficient metadata storage
|
|
||||||
- Optimized lookup mechanisms
|
|
||||||
|
|
||||||
4. **Platform Independence**
|
|
||||||
- Cross-platform compatibility
|
|
||||||
- No platform-specific dependencies
|
|
||||||
- Consistent behavior
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
Add this to your package's `pubspec.yaml` file:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dependencies:
|
dependencies:
|
||||||
platform_reflection: ^0.1.0
|
platform_reflection: ^0.1.0
|
||||||
```
|
```
|
||||||
|
|
||||||
## Core Components
|
## Usage
|
||||||
|
|
||||||
### Reflector
|
### Registration
|
||||||
|
|
||||||
Central management class for reflection operations:
|
Unlike `dart:mirrors`, Platform Reflection requires explicit registration of classes and their members. This enables AOT compilation support and fine-grained control over reflection.
|
||||||
|
|
||||||
```dart
|
|
||||||
class Reflector {
|
|
||||||
// Type registration
|
|
||||||
static void register(Type type);
|
|
||||||
static void registerProperty(Type type, String name, Type propertyType);
|
|
||||||
static void registerMethod(Type type, String name, List<Type> parameterTypes);
|
|
||||||
static void registerConstructor(Type type, String name, {Function? creator});
|
|
||||||
|
|
||||||
// Metadata access
|
|
||||||
static TypeMetadata? getTypeMetadata(Type type);
|
|
||||||
static Map<String, PropertyMetadata>? getPropertyMetadata(Type type);
|
|
||||||
static Map<String, MethodMetadata>? getMethodMetadata(Type type);
|
|
||||||
|
|
||||||
// Utility methods
|
|
||||||
static void reset();
|
|
||||||
static bool isReflectable(Type type);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### RuntimeReflector
|
|
||||||
|
|
||||||
Runtime reflection implementation:
|
|
||||||
|
|
||||||
```dart
|
|
||||||
class RuntimeReflector {
|
|
||||||
// Instance creation
|
|
||||||
InstanceMirror createInstance(Type type, {
|
|
||||||
List<dynamic>? positionalArgs,
|
|
||||||
Map<String, dynamic>? namedArgs,
|
|
||||||
String? constructorName,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Reflection operations
|
|
||||||
InstanceMirror reflect(Object object);
|
|
||||||
ClassMirror reflectClass(Type type);
|
|
||||||
TypeMirror reflectType(Type type);
|
|
||||||
LibraryMirror reflectLibrary(Uri uri);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### LibraryScanner
|
|
||||||
|
|
||||||
Library scanning and analysis:
|
|
||||||
|
|
||||||
```dart
|
|
||||||
class LibraryScanner {
|
|
||||||
// Library scanning
|
|
||||||
static LibraryInfo scanLibrary(Uri uri);
|
|
||||||
|
|
||||||
// Analysis methods
|
|
||||||
static List<FunctionInfo> getTopLevelFunctions(Uri uri);
|
|
||||||
static List<VariableInfo> getTopLevelVariables(Uri uri);
|
|
||||||
static List<DependencyInfo> getDependencies(Uri uri);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage Guide
|
|
||||||
|
|
||||||
### Basic Registration
|
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
@reflectable
|
@reflectable
|
||||||
|
@ -171,71 +49,53 @@ class User {
|
||||||
String name;
|
String name;
|
||||||
int age;
|
int age;
|
||||||
final String id;
|
final String id;
|
||||||
|
List<String> tags;
|
||||||
|
|
||||||
User(this.name, this.age, {required this.id});
|
User(this.name, this.age, {required this.id, List<String>? tags})
|
||||||
|
: tags = tags ?? [];
|
||||||
|
|
||||||
void birthday() {
|
String greet() => "Hi $name!";
|
||||||
age++;
|
|
||||||
|
void addTag(String tag) {
|
||||||
|
tags.add(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
String greet(String greeting) {
|
String getName() => name;
|
||||||
return '$greeting $name!';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register class and members
|
|
||||||
void registerUser() {
|
void registerUser() {
|
||||||
Reflector.register(User);
|
Reflector.register(User);
|
||||||
|
|
||||||
// Register properties
|
|
||||||
Reflector.registerProperty(User, 'name', String);
|
Reflector.registerProperty(User, 'name', String);
|
||||||
Reflector.registerProperty(User, 'age', int);
|
Reflector.registerProperty(User, 'age', int);
|
||||||
Reflector.registerProperty(User, 'id', String, isWritable: false);
|
Reflector.registerProperty(User, 'id', String, isWritable: false);
|
||||||
|
Reflector.registerProperty(User, 'tags', List<String>, isWritable: false);
|
||||||
|
|
||||||
// Register methods
|
Reflector.registerMethod(User, 'greet', [], false);
|
||||||
Reflector.registerMethod(
|
Reflector.registerMethod(User, 'addTag', [String], true);
|
||||||
User,
|
Reflector.registerMethod(User, 'getName', [], false);
|
||||||
'birthday',
|
|
||||||
[],
|
|
||||||
true,
|
|
||||||
parameterNames: [],
|
|
||||||
isRequired: [],
|
|
||||||
);
|
|
||||||
|
|
||||||
Reflector.registerMethod(
|
|
||||||
User,
|
|
||||||
'greet',
|
|
||||||
[String],
|
|
||||||
false,
|
|
||||||
parameterNames: ['greeting'],
|
|
||||||
isRequired: [true],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Register constructor
|
|
||||||
Reflector.registerConstructor(
|
Reflector.registerConstructor(
|
||||||
User,
|
User,
|
||||||
'',
|
'',
|
||||||
parameterTypes: [String, int, String],
|
parameterTypes: [String, int, String, List<String>],
|
||||||
parameterNames: ['name', 'age', 'id'],
|
parameterNames: ['name', 'age', 'id', 'tags'],
|
||||||
isRequired: [true, true, true],
|
isRequired: [true, true, true, false],
|
||||||
isNamed: [false, false, true],
|
isNamed: [false, false, true, true],
|
||||||
creator: (String name, int age, {required String id}) =>
|
|
||||||
User(name, age, id: id),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Instance Manipulation
|
### Reflection Operations
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
void manipulateInstance() {
|
void demonstrateReflection() {
|
||||||
final reflector = RuntimeReflector.instance;
|
final reflector = RuntimeReflector.instance;
|
||||||
|
|
||||||
// Create instance
|
// Create instance
|
||||||
final user = reflector.createInstance(
|
final user = reflector.createInstance(
|
||||||
User,
|
User,
|
||||||
positionalArgs: ['John', 30],
|
positionalArgs: ['John Doe', 30],
|
||||||
namedArgs: {'id': '123'},
|
namedArgs: {'id': 'user1', 'tags': ['admin', 'user']},
|
||||||
) as User;
|
) as User;
|
||||||
|
|
||||||
// Get mirror
|
// Get mirror
|
||||||
|
@ -243,195 +103,20 @@ void manipulateInstance() {
|
||||||
|
|
||||||
// Property access
|
// Property access
|
||||||
final name = mirror.getField(const Symbol('name')).reflectee as String;
|
final name = mirror.getField(const Symbol('name')).reflectee as String;
|
||||||
final age = mirror.getField(const Symbol('age')).reflectee as int;
|
|
||||||
|
|
||||||
// Property modification
|
// Property modification
|
||||||
mirror.setField(const Symbol('name'), 'Jane');
|
mirror.setField(const Symbol('age'), 25);
|
||||||
mirror.setField(const Symbol('age'), 31);
|
|
||||||
|
|
||||||
// Method invocation
|
// Method invocation
|
||||||
mirror.invoke(const Symbol('birthday'), []);
|
final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String;
|
||||||
final greeting = mirror.invoke(
|
|
||||||
const Symbol('greet'),
|
|
||||||
['Hello'],
|
|
||||||
).reflectee as String;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Library Reflection
|
// Type information
|
||||||
|
final classMirror = reflector.reflectClass(User);
|
||||||
|
print('Type name: ${classMirror.name}');
|
||||||
|
|
||||||
```dart
|
// Type relationships
|
||||||
void reflectLibrary() {
|
final entityType = reflector.reflectType(Entity);
|
||||||
final reflector = RuntimeReflector.instance;
|
print('User is subtype of Entity: ${classMirror.isSubclassOf(entityType)}');
|
||||||
|
|
||||||
// Get library mirror
|
|
||||||
final library = reflector.reflectLibrary(
|
|
||||||
Uri.parse('package:myapp/src/models.dart')
|
|
||||||
);
|
|
||||||
|
|
||||||
// Access top-level function
|
|
||||||
final result = library.invoke(
|
|
||||||
const Symbol('utilityFunction'),
|
|
||||||
[arg1, arg2],
|
|
||||||
).reflectee;
|
|
||||||
|
|
||||||
// Access top-level variable
|
|
||||||
final value = library.getField(const Symbol('constant')).reflectee;
|
|
||||||
|
|
||||||
// Get library dependencies
|
|
||||||
final dependencies = library.libraryDependencies;
|
|
||||||
for (final dep in dependencies) {
|
|
||||||
print('Import: ${dep.targetLibrary.uri}');
|
|
||||||
print('Is deferred: ${dep.isDeferred}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Type Relationships
|
|
||||||
|
|
||||||
```dart
|
|
||||||
void checkTypes() {
|
|
||||||
final reflector = RuntimeReflector.instance;
|
|
||||||
|
|
||||||
// Get class mirrors
|
|
||||||
final userMirror = reflector.reflectClass(User);
|
|
||||||
final baseMirror = reflector.reflectClass(BaseClass);
|
|
||||||
|
|
||||||
// Check inheritance
|
|
||||||
final isSubclass = userMirror.isSubclassOf(baseMirror);
|
|
||||||
|
|
||||||
// Check type compatibility
|
|
||||||
final isCompatible = userMirror.isAssignableTo(baseMirror);
|
|
||||||
|
|
||||||
// Get superclass
|
|
||||||
final superclass = userMirror.superclass;
|
|
||||||
|
|
||||||
// Get interfaces
|
|
||||||
final interfaces = userMirror.interfaces;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Advanced Usage
|
|
||||||
|
|
||||||
### Generic Type Handling
|
|
||||||
|
|
||||||
```dart
|
|
||||||
@reflectable
|
|
||||||
class Container<T> {
|
|
||||||
T value;
|
|
||||||
Container(this.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
void handleGenericType() {
|
|
||||||
Reflector.register(Container);
|
|
||||||
|
|
||||||
// Register with specific type
|
|
||||||
final stringContainer = reflector.createInstance(
|
|
||||||
Container,
|
|
||||||
positionalArgs: ['Hello'],
|
|
||||||
) as Container<String>;
|
|
||||||
|
|
||||||
final mirror = reflector.reflect(stringContainer);
|
|
||||||
final value = mirror.getField(const Symbol('value')).reflectee as String;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
|
|
||||||
```dart
|
|
||||||
void demonstrateErrorHandling() {
|
|
||||||
try {
|
|
||||||
// Attempt to reflect unregistered type
|
|
||||||
reflector.reflect(UnregisteredClass());
|
|
||||||
} on NotReflectableException catch (e) {
|
|
||||||
print('Type not registered: $e');
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Attempt to access non-existent member
|
|
||||||
final mirror = reflector.reflect(user);
|
|
||||||
mirror.getField(const Symbol('nonexistent'));
|
|
||||||
} on MemberNotFoundException catch (e) {
|
|
||||||
print('Member not found: $e');
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Attempt invalid method invocation
|
|
||||||
final mirror = reflector.reflect(user);
|
|
||||||
mirror.invoke(const Symbol('greet'), [42]); // Wrong argument type
|
|
||||||
} on InvalidArgumentsException catch (e) {
|
|
||||||
print('Invalid arguments: $e');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Performance Considerations
|
|
||||||
|
|
||||||
### Registration Impact
|
|
||||||
|
|
||||||
- Explicit registration adds startup cost
|
|
||||||
- Improved runtime performance
|
|
||||||
- Reduced memory usage
|
|
||||||
- Controlled reflection surface
|
|
||||||
|
|
||||||
### Optimization Techniques
|
|
||||||
|
|
||||||
1. **Lazy Loading**
|
|
||||||
```dart
|
|
||||||
// Only register when needed
|
|
||||||
if (Reflector.getTypeMetadata(User) == null) {
|
|
||||||
registerUser();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Metadata Caching**
|
|
||||||
```dart
|
|
||||||
// Cache metadata access
|
|
||||||
final metadata = Reflector.getTypeMetadata(User);
|
|
||||||
final properties = metadata.properties;
|
|
||||||
final methods = metadata.methods;
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Instance Reuse**
|
|
||||||
```dart
|
|
||||||
// Reuse instance mirrors
|
|
||||||
final mirror = reflector.reflect(user);
|
|
||||||
// Store mirror for repeated use
|
|
||||||
```
|
|
||||||
|
|
||||||
### Memory Management
|
|
||||||
|
|
||||||
- Cached class mirrors
|
|
||||||
- Efficient parameter resolution
|
|
||||||
- Smart library scanning
|
|
||||||
- Minimal metadata storage
|
|
||||||
|
|
||||||
## Migration Guide
|
|
||||||
|
|
||||||
### From dart:mirrors
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Old dart:mirrors code
|
|
||||||
import 'dart:mirrors';
|
|
||||||
|
|
||||||
final mirror = reflect(instance);
|
|
||||||
final value = mirror.getField(#propertyName).reflectee;
|
|
||||||
|
|
||||||
// New platform_reflection code
|
|
||||||
import 'package:platform_reflection/reflection.dart';
|
|
||||||
|
|
||||||
final mirror = reflector.reflect(instance);
|
|
||||||
final value = mirror.getField(const Symbol('propertyName')).reflectee;
|
|
||||||
```
|
|
||||||
|
|
||||||
### Registration Requirements
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Add registration code
|
|
||||||
void registerTypes() {
|
|
||||||
Reflector.register(MyClass);
|
|
||||||
Reflector.registerProperty(MyClass, 'property', String);
|
|
||||||
Reflector.registerMethod(MyClass, 'method', [int]);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -439,9 +124,8 @@ void registerTypes() {
|
||||||
|
|
||||||
### Core Classes
|
### Core Classes
|
||||||
|
|
||||||
- `Reflector`: Central reflection management
|
- `Reflector`: Static class for registration and metadata management
|
||||||
- `RuntimeReflector`: Runtime reflection operations
|
- `RuntimeReflector`: Runtime reflection operations
|
||||||
- `LibraryScanner`: Library scanning and analysis
|
|
||||||
|
|
||||||
### Mirrors
|
### Mirrors
|
||||||
|
|
||||||
|
@ -460,33 +144,38 @@ void registerTypes() {
|
||||||
|
|
||||||
### Exceptions
|
### Exceptions
|
||||||
|
|
||||||
- `NotReflectableException`
|
- `ReflectionException`: Base exception for reflection errors
|
||||||
- `ReflectionException`
|
- `NotReflectableException`: Thrown when attempting to reflect on an unregistered type
|
||||||
- `InvalidArgumentsException`
|
|
||||||
- `MemberNotFoundException`
|
## Performance Considerations
|
||||||
|
|
||||||
|
- Explicit registration adds startup cost but improves runtime performance
|
||||||
|
- Cached class mirrors for efficient repeated use
|
||||||
|
- Minimal metadata storage for reduced memory footprint
|
||||||
|
- AOT compilation support allows for better optimization
|
||||||
|
|
||||||
## Limitations
|
## Limitations
|
||||||
|
|
||||||
Current Implementation Gaps:
|
- Requires explicit registration of reflectable types and members
|
||||||
|
- Limited support for complex generic types
|
||||||
|
- No support for extension methods
|
||||||
|
- No cross-package private member access
|
||||||
|
|
||||||
1. **Type System**
|
## Migration from dart:mirrors
|
||||||
- Limited generic variance support
|
|
||||||
- Basic type relationship checking
|
|
||||||
|
|
||||||
2. **Reflection Features**
|
To migrate from `dart:mirrors` to Platform Reflection:
|
||||||
- No extension method support
|
|
||||||
- Limited annotation metadata
|
|
||||||
- No cross-package private member access
|
|
||||||
|
|
||||||
3. **Language Features**
|
1. Replace `import 'dart:mirrors'` with `import 'package:platform_reflection/mirrors.dart'`.
|
||||||
- No operator overloading reflection
|
2. Add `@reflectable` annotation to classes you want to reflect on.
|
||||||
- No dynamic code generation
|
3. Implement a registration function for each reflectable class.
|
||||||
- Limited mixin support
|
4. Call registration functions at the start of your application.
|
||||||
|
5. Replace `MirrorSystem.reflect()` with `RuntimeReflector.instance.reflect()`.
|
||||||
|
6. Update any code that relies on automatic discovery of classes or members.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.
|
Contributions are welcome! Please see our [Contributing Guidelines](CONTRIBUTING.md) for more details.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT License - see [LICENSE](LICENSE) for details.
|
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||||
|
|
|
@ -1,203 +1,102 @@
|
||||||
# Platform Reflection Capabilities
|
# Platform Reflection Capabilities
|
||||||
|
|
||||||
|
This document outlines the key capabilities of the Platform Reflection library, demonstrating its features and usage patterns.
|
||||||
|
|
||||||
## Core Reflection Features
|
## Core Reflection Features
|
||||||
|
|
||||||
### 1. Library Reflection
|
### 1. Class Reflection
|
||||||
```dart
|
```dart
|
||||||
// Library reflection support
|
@reflectable
|
||||||
final library = LibraryMirrorImpl.withDeclarations(
|
class User {
|
||||||
name: 'my_library',
|
String name;
|
||||||
uri: Uri.parse('package:my_package/my_library.dart'),
|
int age;
|
||||||
);
|
final String id;
|
||||||
|
List<String> tags;
|
||||||
|
|
||||||
// Access top-level members
|
User(this.name, this.age, {required this.id, List<String>? tags})
|
||||||
final greeting = library.getField(const Symbol('greeting')).reflectee;
|
: tags = tags ?? [];
|
||||||
final sum = library.invoke(
|
|
||||||
const Symbol('add'),
|
String greet() => "Hi $name!";
|
||||||
[1, 2],
|
void addTag(String tag) => tags.add(tag);
|
||||||
).reflectee;
|
String getName() => name;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registration
|
||||||
|
Reflector.register(User);
|
||||||
|
Reflector.registerProperty(User, 'name', String);
|
||||||
|
Reflector.registerProperty(User, 'age', int);
|
||||||
|
Reflector.registerProperty(User, 'id', String, isWritable: false);
|
||||||
|
Reflector.registerProperty(User, 'tags', List<String>, isWritable: false);
|
||||||
|
Reflector.registerMethod(User, 'greet', [], false);
|
||||||
|
Reflector.registerMethod(User, 'addTag', [String], true);
|
||||||
|
Reflector.registerMethod(User, 'getName', [], false);
|
||||||
|
Reflector.registerConstructor(User, '',
|
||||||
|
parameterTypes: [String, int, String, List<String>],
|
||||||
|
parameterNames: ['name', 'age', 'id', 'tags'],
|
||||||
|
isRequired: [true, true, true, false],
|
||||||
|
isNamed: [false, false, true, true],
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Isolate Support
|
### 2. Instance Creation and Manipulation
|
||||||
```dart
|
```dart
|
||||||
// Current isolate reflection
|
final reflector = RuntimeReflector.instance;
|
||||||
final current = IsolateMirrorImpl.current(rootLibrary);
|
|
||||||
|
|
||||||
// Other isolate reflection
|
// Create instance
|
||||||
final other = IsolateMirrorImpl.other(
|
final user = reflector.createInstance(
|
||||||
isolate,
|
User,
|
||||||
'worker',
|
positionalArgs: ['John Doe', 30],
|
||||||
rootLibrary,
|
namedArgs: {'id': 'user1', 'tags': ['admin', 'user']},
|
||||||
);
|
) as User;
|
||||||
|
|
||||||
// Isolate control
|
// Get mirror
|
||||||
await other.pause();
|
final mirror = reflector.reflect(user);
|
||||||
await other.resume();
|
|
||||||
await other.kill();
|
|
||||||
|
|
||||||
// Error handling
|
// Property access and modification
|
||||||
other.addErrorListener((error, stack) {
|
print('Name: ${mirror.getField(const Symbol('name')).reflectee}');
|
||||||
print('Error in isolate: $error\n$stack');
|
mirror.setField(const Symbol('name'), 'Jane Doe');
|
||||||
|
|
||||||
|
// Method invocation
|
||||||
|
final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String;
|
||||||
|
mirror.invoke(const Symbol('addTag'), ['vip']);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Type Information
|
||||||
|
```dart
|
||||||
|
final classMirror = reflector.reflectClass(User);
|
||||||
|
|
||||||
|
print('Type name: ${classMirror.name}');
|
||||||
|
|
||||||
|
// Properties
|
||||||
|
classMirror.declarations.values
|
||||||
|
.whereType<VariableMirror>()
|
||||||
|
.forEach((prop) {
|
||||||
|
print('Property: ${prop.name}: ${prop.type.name}');
|
||||||
|
if (!prop.isFinal && !prop.isWritable) print(' (read-only)');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Exit handling
|
// Methods
|
||||||
other.addExitListener((message) {
|
classMirror.declarations.values
|
||||||
print('Isolate exited with: $message');
|
.whereType<MethodMirror>()
|
||||||
|
.where((method) => !method.isConstructor)
|
||||||
|
.forEach((method) {
|
||||||
|
print('Method: ${method.name}');
|
||||||
});
|
});
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Type System
|
// Constructors
|
||||||
```dart
|
classMirror.declarations.values
|
||||||
// Special types
|
.whereType<MethodMirror>()
|
||||||
final voidType = VoidType.instance;
|
.where((method) => method.isConstructor)
|
||||||
final dynamicType = DynamicType.instance;
|
.forEach((constructor) {
|
||||||
final neverType = NeverType.instance;
|
print('Constructor: ${constructor.name}');
|
||||||
|
});
|
||||||
// Type checking
|
|
||||||
final isVoid = type.isVoid;
|
|
||||||
final isDynamic = type.isDynamic;
|
|
||||||
final isNever = type.isNever;
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Metadata System
|
|
||||||
```dart
|
|
||||||
// Parameter metadata
|
|
||||||
final param = ParameterMetadata(
|
|
||||||
name: 'id',
|
|
||||||
type: int,
|
|
||||||
isRequired: true,
|
|
||||||
isNamed: false,
|
|
||||||
defaultValue: 0,
|
|
||||||
attributes: [deprecated],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Property metadata
|
|
||||||
final prop = PropertyMetadata(
|
|
||||||
name: 'name',
|
|
||||||
type: String,
|
|
||||||
isReadable: true,
|
|
||||||
isWritable: true,
|
|
||||||
attributes: [override],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Method metadata
|
|
||||||
final method = MethodMetadata(
|
|
||||||
name: 'calculate',
|
|
||||||
parameterTypes: [int, double],
|
|
||||||
parameters: [...],
|
|
||||||
isStatic: false,
|
|
||||||
returnsVoid: false,
|
|
||||||
attributes: [deprecated],
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Constructor Support
|
|
||||||
```dart
|
|
||||||
// Constructor metadata
|
|
||||||
final ctor = ConstructorMetadata(
|
|
||||||
name: 'named',
|
|
||||||
parameterTypes: [String, int],
|
|
||||||
parameters: [...],
|
|
||||||
parameterNames: ['name', 'age'],
|
|
||||||
attributes: [...],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Validation
|
|
||||||
final valid = ctor.validateArguments(['John', 42]);
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6. Type Metadata
|
|
||||||
```dart
|
|
||||||
// Full type information
|
|
||||||
final type = TypeMetadata(
|
|
||||||
type: User,
|
|
||||||
name: 'User',
|
|
||||||
properties: {...},
|
|
||||||
methods: {...},
|
|
||||||
constructors: [...],
|
|
||||||
supertype: Person,
|
|
||||||
interfaces: [Comparable],
|
|
||||||
attributes: [serializable],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Member access
|
|
||||||
final prop = type.getProperty('name');
|
|
||||||
final method = type.getMethod('greet');
|
|
||||||
final ctor = type.getConstructor('guest');
|
|
||||||
```
|
|
||||||
|
|
||||||
## Advanced Features
|
|
||||||
|
|
||||||
### 1. Library Dependencies
|
|
||||||
```dart
|
|
||||||
final deps = library.libraryDependencies;
|
|
||||||
for (var dep in deps) {
|
|
||||||
if (dep.isImport) {
|
|
||||||
print('Imports: ${dep.targetLibrary?.uri}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Declaration Access
|
|
||||||
```dart
|
|
||||||
final decls = library.declarations;
|
|
||||||
for (var decl in decls.values) {
|
|
||||||
if (decl is MethodMirror) {
|
|
||||||
print('Method: ${decl.simpleName}');
|
|
||||||
} else if (decl is VariableMirror) {
|
|
||||||
print('Variable: ${decl.simpleName}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Function Metadata
|
|
||||||
```dart
|
|
||||||
final func = FunctionMetadata(
|
|
||||||
parameters: [...],
|
|
||||||
returnsVoid: false,
|
|
||||||
returnType: int,
|
|
||||||
);
|
|
||||||
|
|
||||||
final valid = func.validateArguments([1, 2.0]);
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Reflection Registry
|
|
||||||
```dart
|
|
||||||
// Type registration
|
|
||||||
ReflectionRegistry.registerType(User);
|
|
||||||
|
|
||||||
// Member registration
|
|
||||||
ReflectionRegistry.registerProperty(
|
|
||||||
User,
|
|
||||||
'name',
|
|
||||||
String,
|
|
||||||
isReadable: true,
|
|
||||||
isWritable: true,
|
|
||||||
);
|
|
||||||
|
|
||||||
ReflectionRegistry.registerMethod(
|
|
||||||
User,
|
|
||||||
'greet',
|
|
||||||
[String],
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
|
|
||||||
ReflectionRegistry.registerConstructor(
|
|
||||||
User,
|
|
||||||
'guest',
|
|
||||||
factory,
|
|
||||||
);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Error Handling
|
## Error Handling
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
try {
|
try {
|
||||||
// Reflection operations
|
final mirror = reflector.reflect(unregisteredInstance);
|
||||||
} on MemberNotFoundException catch (e) {
|
|
||||||
print('Member not found: ${e.memberName} on ${e.type}');
|
|
||||||
} on InvalidArgumentsException catch (e) {
|
|
||||||
print('Invalid arguments for ${e.memberName}');
|
|
||||||
} on ReflectionException catch (e) {
|
} on ReflectionException catch (e) {
|
||||||
print('Reflection error: ${e.message}');
|
print('Reflection error: ${e.message}');
|
||||||
}
|
}
|
||||||
|
@ -222,66 +121,34 @@ try {
|
||||||
- Fast lookup mechanisms
|
- Fast lookup mechanisms
|
||||||
- Memory-conscious design
|
- Memory-conscious design
|
||||||
|
|
||||||
3. **Cross-isolate Performance**
|
|
||||||
- Minimal serialization overhead
|
|
||||||
- Efficient isolate communication
|
|
||||||
- Controlled resource usage
|
|
||||||
|
|
||||||
## Security Features
|
|
||||||
|
|
||||||
1. **Access Control**
|
|
||||||
- Controlled reflection surface
|
|
||||||
- Explicit registration required
|
|
||||||
- Member visibility respect
|
|
||||||
|
|
||||||
2. **Type Safety**
|
|
||||||
- Strong type checking
|
|
||||||
- Argument validation
|
|
||||||
- Return type verification
|
|
||||||
|
|
||||||
3. **Isolate Safety**
|
|
||||||
- Controlled isolate access
|
|
||||||
- Error propagation
|
|
||||||
- Resource cleanup
|
|
||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
1. **Registration**
|
1. **Early Registration**
|
||||||
```dart
|
```dart
|
||||||
// Register early
|
|
||||||
void main() {
|
void main() {
|
||||||
registerTypes();
|
registerReflectableTypes();
|
||||||
runApp();
|
runApp();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **Metadata Usage**
|
2. **Caching Mirrors**
|
||||||
```dart
|
```dart
|
||||||
// Cache metadata
|
class UserService {
|
||||||
final metadata = Reflector.getTypeMetadata(User);
|
final Map<User, InstanceMirror> _mirrors = {};
|
||||||
final properties = metadata.properties;
|
|
||||||
final methods = metadata.methods;
|
InstanceMirror getMirror(User user) {
|
||||||
|
return _mirrors.putIfAbsent(user, () => reflector.reflect(user));
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **Error Handling**
|
3. **Comprehensive Error Handling**
|
||||||
```dart
|
```dart
|
||||||
// Comprehensive error handling
|
|
||||||
try {
|
try {
|
||||||
final result = mirror.invoke(name, args);
|
final result = mirror.invoke(const Symbol('method'), args);
|
||||||
} on ReflectionException catch (e) {
|
} on ReflectionException catch (e) {
|
||||||
handleError(e);
|
handleReflectionError(e);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
4. **Isolate Management**
|
This document provides an overview of the Platform Reflection library's capabilities. For detailed API documentation, please refer to the [API Reference](../README.md#api-reference).
|
||||||
```dart
|
|
||||||
// Proper cleanup
|
|
||||||
final isolate = IsolateMirrorImpl.other(...);
|
|
||||||
try {
|
|
||||||
await doWork(isolate);
|
|
||||||
} finally {
|
|
||||||
await isolate.kill();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This document provides a comprehensive overview of the Platform Reflection library's capabilities. For detailed API documentation, see the [API Reference](../README.md#api-reference).
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# Platform Reflection Documentation
|
# Platform Reflection Documentation
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
Platform Reflection is a modern reflection system for Dart that provides runtime type introspection and manipulation capabilities across all platforms.
|
Platform Reflection is a modern reflection system for Dart that provides runtime type introspection and manipulation capabilities across all platforms, including VM, Web, and Flutter.
|
||||||
|
|
||||||
## Documentation Structure
|
## Documentation Structure
|
||||||
|
|
||||||
|
@ -21,19 +21,17 @@ Platform Reflection is a modern reflection system for Dart that provides runtime
|
||||||
1. Basic Usage
|
1. Basic Usage
|
||||||
- [Installation](../README.md#installation)
|
- [Installation](../README.md#installation)
|
||||||
- [Basic Reflection](quick_start.md#basic-usage)
|
- [Basic Reflection](quick_start.md#basic-usage)
|
||||||
- [Property Access](quick_start.md#2-property-access)
|
- [Property Access and Method Invocation](quick_start.md#2-use-reflection)
|
||||||
- [Method Invocation](quick_start.md#3-method-invocation)
|
- [Type Information](quick_start.md#3-type-information)
|
||||||
|
|
||||||
2. Advanced Usage
|
2. Advanced Usage
|
||||||
- [Type Information](quick_start.md#5-type-information)
|
- [Error Handling](quick_start.md#error-handling)
|
||||||
- [Error Handling](quick_start.md#6-error-handling)
|
|
||||||
- [Common Patterns](quick_start.md#common-patterns)
|
|
||||||
- [Best Practices](quick_start.md#best-practices)
|
- [Best Practices](quick_start.md#best-practices)
|
||||||
|
- [Performance Tips](quick_start.md#performance-tips)
|
||||||
|
|
||||||
3. Performance
|
3. Performance
|
||||||
- [Optimization Techniques](technical_specification.md#performance-optimizations)
|
- [Optimization Techniques](technical_specification.md#performance-optimizations)
|
||||||
- [Performance Tips](quick_start.md#performance-tips)
|
- [Performance Considerations](capabilities.md#performance-considerations)
|
||||||
- [Memory Management](technical_specification.md#memory-management)
|
|
||||||
|
|
||||||
### Implementation Status
|
### Implementation Status
|
||||||
|
|
||||||
|
@ -45,23 +43,19 @@ Platform Reflection is a modern reflection system for Dart that provides runtime
|
||||||
✅ Type introspection
|
✅ Type introspection
|
||||||
✅ Basic metadata support
|
✅ Basic metadata support
|
||||||
✅ Error handling
|
✅ Error handling
|
||||||
✅ Cross-platform support
|
✅ Cross-platform support (VM, Web, Flutter)
|
||||||
|
|
||||||
#### Known Limitations
|
#### Known Limitations
|
||||||
❌ No cross-isolate reflection
|
|
||||||
❌ Limited generic support
|
❌ Limited generic support
|
||||||
❌ No source location tracking
|
|
||||||
❌ No extension method support
|
❌ No extension method support
|
||||||
❌ No mixin composition
|
|
||||||
❌ Limited metadata capabilities
|
❌ Limited metadata capabilities
|
||||||
❌ No dynamic proxy generation
|
❌ No dynamic proxy generation
|
||||||
❌ No attribute-based reflection
|
|
||||||
|
|
||||||
### Development
|
### Development
|
||||||
|
|
||||||
1. Contributing
|
1. Contributing
|
||||||
- [Getting Started](roadmap.md#getting-started)
|
|
||||||
- [Priority Areas](roadmap.md#priority-areas)
|
- [Priority Areas](roadmap.md#priority-areas)
|
||||||
|
- [Getting Started](roadmap.md#getting-started)
|
||||||
- [Development Process](roadmap.md#development-process)
|
- [Development Process](roadmap.md#development-process)
|
||||||
|
|
||||||
2. Future Plans
|
2. Future Plans
|
||||||
|
@ -77,9 +71,7 @@ Platform Reflection is a modern reflection system for Dart that provides runtime
|
||||||
- [Performance Tips](quick_start.md#performance-tips)
|
- [Performance Tips](quick_start.md#performance-tips)
|
||||||
|
|
||||||
2. Version Support
|
2. Version Support
|
||||||
- [Support Matrix](roadmap.md#version-support-matrix)
|
|
||||||
- [Breaking Changes](roadmap.md#breaking-changes)
|
- [Breaking Changes](roadmap.md#breaking-changes)
|
||||||
- [Migration Support](roadmap.md#migration-support)
|
|
||||||
|
|
||||||
## Quick Links
|
## Quick Links
|
||||||
|
|
||||||
|
@ -93,13 +85,12 @@ Platform Reflection is a modern reflection system for Dart that provides runtime
|
||||||
1. Review the [Technical Specification](technical_specification.md)
|
1. Review the [Technical Specification](technical_specification.md)
|
||||||
2. Check the [Development Roadmap](roadmap.md)
|
2. Check the [Development Roadmap](roadmap.md)
|
||||||
3. See [Priority Areas](roadmap.md#priority-areas)
|
3. See [Priority Areas](roadmap.md#priority-areas)
|
||||||
4. Read [Contributing Guidelines](../CONTRIBUTING.md)
|
4. Read Contributing Guidelines (../CONTRIBUTING.md)
|
||||||
|
|
||||||
### For Framework Developers
|
### For Framework Developers
|
||||||
1. Study the [Mirrors Comparison](mirrors_comparison.md)
|
1. Study the [Mirrors Comparison](mirrors_comparison.md)
|
||||||
2. Review [Implementation Details](technical_specification.md#implementation-details)
|
2. Review [Implementation Details](technical_specification.md#implementation-details)
|
||||||
3. Check [Framework Integration](roadmap.md#framework-integration)
|
3. Check [Framework Integration](roadmap.md#2-framework-integration)
|
||||||
4. See [Enterprise Features](roadmap.md#enterprise-features)
|
|
||||||
|
|
||||||
## Document Updates
|
## Document Updates
|
||||||
|
|
||||||
|
|
|
@ -1,41 +1,21 @@
|
||||||
# Dart Mirrors vs Platform Reflection Comparison
|
# Dart Mirrors vs Platform Reflection Comparison
|
||||||
|
|
||||||
|
This document compares our Platform Reflection library with Dart's built-in `dart:mirrors` package, highlighting key differences, trade-offs, and migration paths.
|
||||||
|
|
||||||
## Core Features Comparison
|
## Core Features Comparison
|
||||||
|
|
||||||
| Feature | dart:mirrors | Platform Reflection | Notes |
|
| Feature | dart:mirrors | Platform Reflection | Notes |
|
||||||
|---------|-------------|-------------------|--------|
|
|---------|--------------|---------------------|-------|
|
||||||
| **Library Reflection** |
|
| Class Reflection | ✅ Full | ✅ Full | Requires registration in Platform Reflection |
|
||||||
| Top-level functions | ✅ Full | ✅ Full | Complete parity |
|
| Method Invocation | ✅ Full | ✅ Full | Complete parity |
|
||||||
| Top-level variables | ✅ Full | ✅ Full | Complete parity |
|
| Property Access | ✅ Full | ✅ Full | Complete parity |
|
||||||
| Library dependencies | ✅ Full | ✅ Full | Complete parity |
|
| Constructor Invocation | ✅ Full | ✅ Full | Requires registration in Platform Reflection |
|
||||||
| URI resolution | ✅ Full | ✅ Full | Complete parity |
|
| Type Information | ✅ Full | ✅ Full | Complete parity |
|
||||||
|
| Metadata | ✅ Full | ⚠️ Limited | Basic metadata support in Platform Reflection |
|
||||||
|
| Generic Types | ✅ Full | ⚠️ Limited | Basic generic support in Platform Reflection |
|
||||||
|
| AOT Compilation | ❌ No | ✅ Yes | Platform Reflection supports AOT compilation |
|
||||||
|
|
||||||
| Feature | dart:mirrors | Platform Reflection | Notes |
|
## Key Implementation Differences
|
||||||
|---------|-------------|-------------------|--------|
|
|
||||||
| **Isolate Support** |
|
|
||||||
| Current isolate | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Other isolates | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Isolate control | ✅ Full | ✅ Full | Pause/Resume/Kill |
|
|
||||||
| Error handling | ✅ Full | ✅ Full | Error/Exit listeners |
|
|
||||||
|
|
||||||
| Feature | dart:mirrors | Platform Reflection | Notes |
|
|
||||||
|---------|-------------|-------------------|--------|
|
|
||||||
| **Type System** |
|
|
||||||
| Special types | ✅ Full | ✅ Full | void/dynamic/never |
|
|
||||||
| Type relationships | ✅ Full | ✅ Full | Complete type checking |
|
|
||||||
| Generic types | ✅ Full | ⚠️ Limited | Basic generic support |
|
|
||||||
| Type parameters | ✅ Full | ⚠️ Limited | Basic parameter support |
|
|
||||||
|
|
||||||
| Feature | dart:mirrors | Platform Reflection | Notes |
|
|
||||||
|---------|-------------|-------------------|--------|
|
|
||||||
| **Metadata System** |
|
|
||||||
| Class metadata | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Method metadata | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Property metadata | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Parameter metadata | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
| Custom attributes | ✅ Full | ✅ Full | Complete parity |
|
|
||||||
|
|
||||||
## Implementation Differences
|
|
||||||
|
|
||||||
### Registration System
|
### Registration System
|
||||||
|
|
||||||
|
@ -53,55 +33,34 @@ class MyClass {}
|
||||||
Reflector.register(MyClass);
|
Reflector.register(MyClass);
|
||||||
Reflector.registerProperty(MyClass, 'prop', String);
|
Reflector.registerProperty(MyClass, 'prop', String);
|
||||||
Reflector.registerMethod(MyClass, 'method', [int]);
|
Reflector.registerMethod(MyClass, 'method', [int]);
|
||||||
|
Reflector.registerConstructor(MyClass, '', parameterTypes: []);
|
||||||
```
|
```
|
||||||
|
|
||||||
### Library Access
|
### Reflection Usage
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
// dart:mirrors
|
// dart:mirrors
|
||||||
final lib = MirrorSystem.findLibrary('my_lib');
|
import 'dart:mirrors';
|
||||||
|
|
||||||
|
final instance = MyClass();
|
||||||
|
final mirror = reflect(instance);
|
||||||
|
final value = mirror.getField(#prop).reflectee;
|
||||||
|
mirror.invoke(#method, [42]);
|
||||||
|
|
||||||
// Platform Reflection
|
// Platform Reflection
|
||||||
final lib = LibraryMirrorImpl.withDeclarations(
|
import 'package:platform_reflection/mirrors.dart';
|
||||||
name: 'my_lib',
|
|
||||||
uri: Uri.parse('package:my_package/my_lib.dart'),
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Isolate Handling
|
final reflector = RuntimeReflector.instance;
|
||||||
|
final instance = reflector.createInstance(MyClass, positionalArgs: []) as MyClass;
|
||||||
```dart
|
final mirror = reflector.reflect(instance);
|
||||||
// dart:mirrors
|
final value = mirror.getField(const Symbol('prop')).reflectee;
|
||||||
final mirror = reflect(isolate);
|
mirror.invoke(const Symbol('method'), [42]);
|
||||||
await mirror.invoke(#method, []);
|
|
||||||
|
|
||||||
// Platform Reflection
|
|
||||||
final mirror = IsolateMirrorImpl.other(isolate, 'name', lib);
|
|
||||||
mirror.addErrorListener((error, stack) {
|
|
||||||
// Handle error
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Type System
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// dart:mirrors
|
|
||||||
final type = reflectType(MyClass);
|
|
||||||
final isSubtype = type.isSubtypeOf(otherType);
|
|
||||||
|
|
||||||
// Platform Reflection
|
|
||||||
final type = TypeMetadata(
|
|
||||||
type: MyClass,
|
|
||||||
name: 'MyClass',
|
|
||||||
// ...
|
|
||||||
);
|
|
||||||
final isSubtype = type.supertype == otherType;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Performance Characteristics
|
## Performance Characteristics
|
||||||
|
|
||||||
| Aspect | dart:mirrors | Platform Reflection | Winner |
|
| Aspect | dart:mirrors | Platform Reflection | Winner |
|
||||||
|--------|-------------|-------------------|---------|
|
|--------|--------------|---------------------|--------|
|
||||||
| Startup time | ❌ Slower | ✅ Faster | Platform Reflection |
|
| Startup time | ❌ Slower | ✅ Faster | Platform Reflection |
|
||||||
| Runtime performance | ❌ Slower | ✅ Faster | Platform Reflection |
|
| Runtime performance | ❌ Slower | ✅ Faster | Platform Reflection |
|
||||||
| Memory usage | ❌ Higher | ✅ Lower | Platform Reflection |
|
| Memory usage | ❌ Higher | ✅ Lower | Platform Reflection |
|
||||||
|
@ -110,7 +69,7 @@ final isSubtype = type.supertype == otherType;
|
||||||
## Platform Support
|
## Platform Support
|
||||||
|
|
||||||
| Platform | dart:mirrors | Platform Reflection | Winner |
|
| Platform | dart:mirrors | Platform Reflection | Winner |
|
||||||
|----------|-------------|-------------------|---------|
|
|----------|--------------|---------------------|--------|
|
||||||
| VM | ✅ Yes | ✅ Yes | Tie |
|
| VM | ✅ Yes | ✅ Yes | Tie |
|
||||||
| Web | ❌ No | ✅ Yes | Platform Reflection |
|
| Web | ❌ No | ✅ Yes | Platform Reflection |
|
||||||
| Flutter | ❌ No | ✅ Yes | Platform Reflection |
|
| Flutter | ❌ No | ✅ Yes | Platform Reflection |
|
||||||
|
@ -119,91 +78,84 @@ final isSubtype = type.supertype == otherType;
|
||||||
## Use Cases
|
## Use Cases
|
||||||
|
|
||||||
| Use Case | dart:mirrors | Platform Reflection | Better Choice |
|
| Use Case | dart:mirrors | Platform Reflection | Better Choice |
|
||||||
|----------|-------------|-------------------|---------------|
|
|----------|--------------|---------------------|---------------|
|
||||||
| Dependency injection | ✅ Simpler | ⚠️ More setup | dart:mirrors |
|
| Dependency injection | ✅ Simpler | ⚠️ More setup | Depends on platform needs |
|
||||||
| Serialization | ✅ Simpler | ⚠️ More setup | dart:mirrors |
|
| Serialization | ✅ Simpler | ⚠️ More setup | Depends on platform needs |
|
||||||
| Testing/Mocking | ✅ More flexible | ✅ More controlled | Depends on needs |
|
| Testing/Mocking | ✅ More flexible | ✅ More controlled | Depends on needs |
|
||||||
| Production apps | ❌ Limited platforms | ✅ All platforms | Platform Reflection |
|
| Production apps | ❌ Limited platforms | ✅ All platforms | Platform Reflection |
|
||||||
|
|
||||||
## Migration Path
|
## Migration Path
|
||||||
|
|
||||||
### From dart:mirrors
|
To migrate from dart:mirrors to Platform Reflection:
|
||||||
|
|
||||||
1. Add registration:
|
1. Replace imports:
|
||||||
```dart
|
```dart
|
||||||
// Before
|
// Before
|
||||||
@reflectable
|
import 'dart:mirrors';
|
||||||
class MyClass {}
|
|
||||||
|
|
||||||
// After
|
// After
|
||||||
@reflectable
|
import 'package:platform_reflection/mirrors.dart';
|
||||||
class MyClass {}
|
```
|
||||||
|
|
||||||
void register() {
|
2. Add registration for each reflectable class:
|
||||||
|
```dart
|
||||||
|
void registerReflectables() {
|
||||||
Reflector.register(MyClass);
|
Reflector.register(MyClass);
|
||||||
// Register members...
|
Reflector.registerProperty(MyClass, 'prop', String);
|
||||||
}
|
Reflector.registerMethod(MyClass, 'method', [int]);
|
||||||
```
|
Reflector.registerConstructor(MyClass, '', parameterTypes: []);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
2. Update reflection calls:
|
3. Update reflection calls:
|
||||||
```dart
|
```dart
|
||||||
// Before
|
// Before
|
||||||
final mirror = reflect(instance);
|
final mirror = reflect(instance);
|
||||||
final value = mirror.getField(#prop);
|
final value = mirror.getField(#prop).reflectee;
|
||||||
|
|
||||||
// After
|
// After
|
||||||
final mirror = reflector.reflect(instance);
|
final reflector = RuntimeReflector.instance;
|
||||||
final value = mirror.getField(const Symbol('prop'));
|
final mirror = reflector.reflect(instance);
|
||||||
```
|
final value = mirror.getField(const Symbol('prop')).reflectee;
|
||||||
|
```
|
||||||
|
|
||||||
3. Handle libraries:
|
4. Replace MirrorSystem usage:
|
||||||
```dart
|
```dart
|
||||||
// Before
|
// Before
|
||||||
final lib = MirrorSystem.findLibrary('my_lib');
|
final classMirror = reflectClass(MyClass);
|
||||||
|
|
||||||
// After
|
// After
|
||||||
final lib = LibraryMirrorImpl.withDeclarations(
|
final classMirror = RuntimeReflector.instance.reflectClass(MyClass);
|
||||||
name: 'my_lib',
|
```
|
||||||
uri: uri,
|
|
||||||
);
|
5. Update your build process to ensure registration functions are called at startup.
|
||||||
```
|
|
||||||
|
|
||||||
## Trade-offs
|
## Trade-offs
|
||||||
|
|
||||||
### Advantages of Platform Reflection
|
### Advantages of Platform Reflection
|
||||||
1. Works everywhere
|
1. Works on all platforms (VM, Web, Flutter, AOT)
|
||||||
2. Better performance
|
2. Better performance and smaller code size
|
||||||
3. Smaller code size
|
3. Supports AOT compilation
|
||||||
4. Better tree shaking
|
4. More controlled reflection surface
|
||||||
5. Full isolate support
|
|
||||||
6. Production-ready
|
|
||||||
|
|
||||||
### Advantages of dart:mirrors
|
### Advantages of dart:mirrors
|
||||||
1. No registration needed
|
1. No registration needed
|
||||||
2. Simpler API
|
2. More dynamic capabilities
|
||||||
3. More dynamic capabilities
|
3. Simpler API for some use cases
|
||||||
4. Better for development tools
|
4. Better for certain development tools
|
||||||
5. More flexible
|
|
||||||
|
|
||||||
## Conclusion
|
## Conclusion
|
||||||
|
|
||||||
Platform Reflection offers a more production-ready alternative to dart:mirrors with:
|
Platform Reflection offers a production-ready alternative to dart:mirrors with cross-platform support, better performance, and AOT compilation compatibility. The main trade-off is the need for explicit registration, which provides more control but requires more setup.
|
||||||
- Full cross-platform support
|
|
||||||
- Better performance characteristics
|
|
||||||
- More controlled reflection surface
|
|
||||||
- Full isolate support
|
|
||||||
- Production-ready features
|
|
||||||
|
|
||||||
The main trade-off is the need for explicit registration, but this brings benefits in terms of performance, code size, and tree shaking.
|
|
||||||
|
|
||||||
Choose Platform Reflection when:
|
Choose Platform Reflection when:
|
||||||
- You need cross-platform support
|
- You need cross-platform or AOT compilation support
|
||||||
- Performance is critical
|
- Performance and code size are critical
|
||||||
- Code size matters
|
- You want more control over the reflection surface
|
||||||
- You want production-ready reflection
|
|
||||||
|
|
||||||
Choose dart:mirrors when:
|
Consider dart:mirrors when:
|
||||||
- You're only targeting the VM
|
- You're only targeting the Dart VM
|
||||||
- Development time is critical
|
- You need maximum runtime flexibility
|
||||||
- You need maximum flexibility
|
- You're building certain types of development tools
|
||||||
- You're building development tools
|
|
||||||
|
Remember, the choice between Platform Reflection and dart:mirrors often comes down to your specific platform requirements and performance needs.
|
||||||
|
|
|
@ -1,22 +1,29 @@
|
||||||
# Platform Reflection Quick Start Guide
|
# Platform Reflection Quick Start Guide
|
||||||
|
|
||||||
This guide covers the most common use cases for Platform Reflection to help you get started quickly.
|
This guide covers the essential steps to get started with Platform Reflection, a drop-in replacement for dart:mirrors with AOT compilation support.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
Add this to your package's `pubspec.yaml` file:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
dependencies:
|
dependencies:
|
||||||
platform_reflection: ^0.1.0
|
platform_reflection: ^0.1.0
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Key Concepts
|
||||||
|
|
||||||
|
1. **Explicit Registration**: Unlike dart:mirrors, Platform Reflection requires explicit registration of classes and their members.
|
||||||
|
2. **AOT Compilation Support**: The registration process enables AOT compilation, which dart:mirrors doesn't support.
|
||||||
|
3. **API Similarity**: The reflection API is similar to dart:mirrors, easing the transition.
|
||||||
|
|
||||||
## Basic Usage
|
## Basic Usage
|
||||||
|
|
||||||
### 1. Simple Class Reflection
|
### 1. Define and Register a Class
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
import 'package:platform_reflection/reflection.dart';
|
import 'package:platform_reflection/mirrors.dart';
|
||||||
|
|
||||||
// 1. Define your class
|
|
||||||
@reflectable
|
@reflectable
|
||||||
class User {
|
class User {
|
||||||
String name;
|
String name;
|
||||||
|
@ -24,346 +31,80 @@ class User {
|
||||||
|
|
||||||
User(this.name, this.age);
|
User(this.name, this.age);
|
||||||
|
|
||||||
void birthday() => age++;
|
String greet() => "Hello, $name!";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Register for reflection
|
void registerUser() {
|
||||||
void main() {
|
|
||||||
// Register class
|
|
||||||
Reflector.register(User);
|
Reflector.register(User);
|
||||||
|
|
||||||
// Register properties
|
|
||||||
Reflector.registerProperty(User, 'name', String);
|
Reflector.registerProperty(User, 'name', String);
|
||||||
Reflector.registerProperty(User, 'age', int);
|
Reflector.registerProperty(User, 'age', int);
|
||||||
|
Reflector.registerMethod(User, 'greet', [], false);
|
||||||
// Register methods
|
|
||||||
Reflector.registerMethod(
|
|
||||||
User,
|
|
||||||
'birthday',
|
|
||||||
[],
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Register constructor
|
|
||||||
Reflector.registerConstructor(
|
Reflector.registerConstructor(
|
||||||
User,
|
User,
|
||||||
'',
|
'',
|
||||||
parameterTypes: [String, int],
|
parameterTypes: [String, int],
|
||||||
parameterNames: ['name', 'age'],
|
parameterNames: ['name', 'age'],
|
||||||
creator: (String name, int age) => User(name, age),
|
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Use reflection
|
void main() {
|
||||||
|
registerUser();
|
||||||
|
// Your application code here
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Use Reflection
|
||||||
|
|
||||||
|
```dart
|
||||||
|
void demonstrateReflection() {
|
||||||
|
final reflector = RuntimeReflector.instance;
|
||||||
|
|
||||||
|
// Create instance
|
||||||
final user = reflector.createInstance(
|
final user = reflector.createInstance(
|
||||||
User,
|
User,
|
||||||
positionalArgs: ['John', 30],
|
positionalArgs: ['John Doe', 30],
|
||||||
) as User;
|
) as User;
|
||||||
|
|
||||||
|
// Get mirror
|
||||||
final mirror = reflector.reflect(user);
|
final mirror = reflector.reflect(user);
|
||||||
print(mirror.getField(const Symbol('name')).reflectee); // John
|
|
||||||
mirror.invoke(const Symbol('birthday'), []);
|
// Property access and modification
|
||||||
print(mirror.getField(const Symbol('age')).reflectee); // 31
|
print('Name: ${mirror.getField(const Symbol('name')).reflectee}');
|
||||||
|
mirror.setField(const Symbol('age'), 31);
|
||||||
|
|
||||||
|
// Method invocation
|
||||||
|
final greeting = mirror.invoke(const Symbol('greet'), []).reflectee as String;
|
||||||
|
print(greeting);
|
||||||
|
|
||||||
|
// Type information
|
||||||
|
final classMirror = reflector.reflectClass(User);
|
||||||
|
print('Type name: ${classMirror.name}');
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Property Access
|
## Key Differences from dart:mirrors
|
||||||
|
|
||||||
```dart
|
1. **Registration**: You must register classes, properties, methods, and constructors explicitly.
|
||||||
// Get property value
|
2. **Reflector Class**: Use the `Reflector` class for registration and the `RuntimeReflector` for reflection operations.
|
||||||
final mirror = reflector.reflect(instance);
|
3. **Limited Automatic Discovery**: There's no automatic discovery of classes or members; everything must be registered.
|
||||||
final name = mirror.getField(const Symbol('name')).reflectee as String;
|
|
||||||
|
|
||||||
// Set property value
|
|
||||||
mirror.setField(const Symbol('name'), 'Jane');
|
|
||||||
|
|
||||||
// Check if property exists
|
|
||||||
final metadata = Reflector.getPropertyMetadata(User);
|
|
||||||
if (metadata?.containsKey('name') ?? false) {
|
|
||||||
// Property exists
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Method Invocation
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Invoke method without arguments
|
|
||||||
mirror.invoke(const Symbol('birthday'), []);
|
|
||||||
|
|
||||||
// Invoke method with arguments
|
|
||||||
final result = mirror.invoke(
|
|
||||||
const Symbol('greet'),
|
|
||||||
['Hello'],
|
|
||||||
).reflectee as String;
|
|
||||||
|
|
||||||
// Invoke method with named arguments
|
|
||||||
final result = mirror.invoke(
|
|
||||||
const Symbol('update'),
|
|
||||||
[],
|
|
||||||
{const Symbol('value'): 42},
|
|
||||||
).reflectee;
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Constructor Usage
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Default constructor
|
|
||||||
final instance = reflector.createInstance(
|
|
||||||
User,
|
|
||||||
positionalArgs: ['John', 30],
|
|
||||||
) as User;
|
|
||||||
|
|
||||||
// Named constructor
|
|
||||||
final instance = reflector.createInstance(
|
|
||||||
User,
|
|
||||||
constructorName: 'guest',
|
|
||||||
) as User;
|
|
||||||
|
|
||||||
// Constructor with named arguments
|
|
||||||
final instance = reflector.createInstance(
|
|
||||||
User,
|
|
||||||
positionalArgs: ['John'],
|
|
||||||
namedArgs: {const Symbol('age'): 30},
|
|
||||||
) as User;
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Type Information
|
|
||||||
|
|
||||||
```dart
|
|
||||||
// Get type metadata
|
|
||||||
final metadata = Reflector.getTypeMetadata(User);
|
|
||||||
|
|
||||||
// Check properties
|
|
||||||
for (var property in metadata.properties.values) {
|
|
||||||
print('${property.name}: ${property.type}');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check methods
|
|
||||||
for (var method in metadata.methods.values) {
|
|
||||||
print('${method.name}(${method.parameterTypes.join(', ')})');
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6. Error Handling
|
|
||||||
|
|
||||||
```dart
|
|
||||||
try {
|
|
||||||
// Attempt reflection
|
|
||||||
final mirror = reflector.reflect(instance);
|
|
||||||
mirror.invoke(const Symbol('method'), []);
|
|
||||||
} on NotReflectableException catch (e) {
|
|
||||||
print('Type not registered: $e');
|
|
||||||
} on MemberNotFoundException catch (e) {
|
|
||||||
print('Member not found: $e');
|
|
||||||
} on InvalidArgumentsException catch (e) {
|
|
||||||
print('Invalid arguments: $e');
|
|
||||||
} on ReflectionException catch (e) {
|
|
||||||
print('Reflection error: $e');
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Common Patterns
|
|
||||||
|
|
||||||
### 1. Registration Helper
|
|
||||||
|
|
||||||
```dart
|
|
||||||
void registerType<T>(Type type) {
|
|
||||||
Reflector.register(type);
|
|
||||||
|
|
||||||
final scanner = Scanner();
|
|
||||||
final metadata = scanner.scanType(type);
|
|
||||||
|
|
||||||
// Register properties
|
|
||||||
for (var property in metadata.properties.values) {
|
|
||||||
Reflector.registerProperty(
|
|
||||||
type,
|
|
||||||
property.name,
|
|
||||||
property.type,
|
|
||||||
isWritable: property.isWritable,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Register methods
|
|
||||||
for (var method in metadata.methods.values) {
|
|
||||||
Reflector.registerMethod(
|
|
||||||
type,
|
|
||||||
method.name,
|
|
||||||
method.parameterTypes,
|
|
||||||
method.returnsVoid,
|
|
||||||
parameterNames: method.parameters.map((p) => p.name).toList(),
|
|
||||||
isRequired: method.parameters.map((p) => p.isRequired).toList(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Property Observer
|
|
||||||
|
|
||||||
```dart
|
|
||||||
class PropertyObserver {
|
|
||||||
final InstanceMirror mirror;
|
|
||||||
final Symbol propertyName;
|
|
||||||
final void Function(dynamic oldValue, dynamic newValue) onChange;
|
|
||||||
|
|
||||||
PropertyObserver(this.mirror, this.propertyName, this.onChange);
|
|
||||||
|
|
||||||
void observe() {
|
|
||||||
var lastValue = mirror.getField(propertyName).reflectee;
|
|
||||||
|
|
||||||
Timer.periodic(Duration(milliseconds: 100), (_) {
|
|
||||||
final currentValue = mirror.getField(propertyName).reflectee;
|
|
||||||
if (currentValue != lastValue) {
|
|
||||||
onChange(lastValue, currentValue);
|
|
||||||
lastValue = currentValue;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Method Interceptor
|
|
||||||
|
|
||||||
```dart
|
|
||||||
class MethodInterceptor {
|
|
||||||
final InstanceMirror mirror;
|
|
||||||
final Symbol methodName;
|
|
||||||
final void Function(List args, Map<Symbol, dynamic> named) beforeInvoke;
|
|
||||||
final void Function(dynamic result) afterInvoke;
|
|
||||||
|
|
||||||
MethodInterceptor(
|
|
||||||
this.mirror,
|
|
||||||
this.methodName,
|
|
||||||
{this.beforeInvoke = _noOp,
|
|
||||||
this.afterInvoke = _noOp});
|
|
||||||
|
|
||||||
static void _noOp([dynamic _]) {}
|
|
||||||
|
|
||||||
dynamic invoke(List args, [Map<Symbol, dynamic>? named]) {
|
|
||||||
beforeInvoke(args, named ?? {});
|
|
||||||
final result = mirror.invoke(methodName, args, named).reflectee;
|
|
||||||
afterInvoke(result);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
1. **Register Early**
|
1. Register all reflectable types at application startup.
|
||||||
```dart
|
2. Cache instance mirrors for repeated operations on the same object.
|
||||||
void main() {
|
3. Always handle potential `ReflectionException`s in your code.
|
||||||
// Register all types at startup
|
4. Use reflection judiciously, as it can impact performance.
|
||||||
registerType<User>();
|
|
||||||
registerType<Order>();
|
|
||||||
registerType<Product>();
|
|
||||||
|
|
||||||
// Start application
|
## Common Pitfalls
|
||||||
runApp();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Cache Mirrors**
|
1. Forgetting to register a class or its members before reflection.
|
||||||
```dart
|
2. Attempting to reflect on private members (not supported).
|
||||||
class UserService {
|
3. Not handling potential exceptions during reflection operations.
|
||||||
final Map<User, InstanceMirror> _mirrors = {};
|
|
||||||
|
|
||||||
InstanceMirror getMirror(User user) {
|
|
||||||
return _mirrors.putIfAbsent(
|
|
||||||
user,
|
|
||||||
() => reflector.reflect(user),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Handle Errors**
|
|
||||||
```dart
|
|
||||||
T reflectSafely<T>(Function() operation, T defaultValue) {
|
|
||||||
try {
|
|
||||||
return operation() as T;
|
|
||||||
} on ReflectionException catch (e) {
|
|
||||||
print('Reflection failed: $e');
|
|
||||||
return defaultValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
4. **Validate Registration**
|
|
||||||
```dart
|
|
||||||
bool isFullyRegistered(Type type) {
|
|
||||||
final metadata = Reflector.getTypeMetadata(type);
|
|
||||||
if (metadata == null) return false;
|
|
||||||
|
|
||||||
// Check properties
|
|
||||||
if (metadata.properties.isEmpty) return false;
|
|
||||||
|
|
||||||
// Check methods
|
|
||||||
if (metadata.methods.isEmpty) return false;
|
|
||||||
|
|
||||||
// Check constructors
|
|
||||||
if (metadata.constructors.isEmpty) return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Common Issues
|
|
||||||
|
|
||||||
1. **Type Not Registered**
|
|
||||||
```dart
|
|
||||||
// Wrong
|
|
||||||
reflector.reflect(unregisteredInstance);
|
|
||||||
|
|
||||||
// Right
|
|
||||||
Reflector.register(UnregisteredType);
|
|
||||||
reflector.reflect(instance);
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Missing Property/Method Registration**
|
|
||||||
```dart
|
|
||||||
// Wrong
|
|
||||||
Reflector.register(User);
|
|
||||||
|
|
||||||
// Right
|
|
||||||
Reflector.register(User);
|
|
||||||
Reflector.registerProperty(User, 'name', String);
|
|
||||||
Reflector.registerMethod(User, 'greet', [String]);
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Wrong Argument Types**
|
|
||||||
```dart
|
|
||||||
// Wrong
|
|
||||||
mirror.invoke(const Symbol('greet'), [42]);
|
|
||||||
|
|
||||||
// Right
|
|
||||||
mirror.invoke(const Symbol('greet'), ['Hello']);
|
|
||||||
```
|
|
||||||
|
|
||||||
## Performance Tips
|
|
||||||
|
|
||||||
1. **Cache Metadata**
|
|
||||||
```dart
|
|
||||||
final metadata = Reflector.getTypeMetadata(User);
|
|
||||||
final properties = metadata.properties;
|
|
||||||
final methods = metadata.methods;
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Reuse Mirrors**
|
|
||||||
```dart
|
|
||||||
final mirror = reflector.reflect(instance);
|
|
||||||
// Reuse mirror for multiple operations
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Batch Registration**
|
|
||||||
```dart
|
|
||||||
void registerAll() {
|
|
||||||
for (var type in types) {
|
|
||||||
registerType(type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Next Steps
|
## Next Steps
|
||||||
|
|
||||||
- Read the [Technical Specification](technical_specification.md) for detailed implementation information
|
- Review the [API Reference](../README.md#api-reference) for detailed information.
|
||||||
- Check the [API Reference](../README.md#api-reference) for complete API documentation
|
- Explore the [examples](../example) directory for more complex scenarios.
|
||||||
- See the [Mirrors Comparison](mirrors_comparison.md) for differences from dart:mirrors
|
- If migrating from dart:mirrors, check the [Migration Guide](mirrors_comparison.md) for a detailed comparison and transition tips.
|
||||||
|
|
||||||
|
Remember, Platform Reflection aims to provide the power of reflection with the benefits of AOT compilation. The trade-off is the need for explicit registration, which gives you more control over what can be reflected upon in your application.
|
||||||
|
|
|
@ -1,294 +1,175 @@
|
||||||
# Platform Reflection Roadmap
|
# Platform Reflection Roadmap
|
||||||
|
|
||||||
This document outlines the planned improvements and future direction of the Platform Reflection library.
|
This document outlines the current status, planned improvements, and future direction of the Platform Reflection library.
|
||||||
|
|
||||||
## Current Status (v0.1.0)
|
## Current Status (v0.1.0)
|
||||||
|
|
||||||
### Implemented Features
|
### Implemented Features
|
||||||
✅ Basic reflection system
|
✅ Core reflection system with explicit registration
|
||||||
✅ Property access/mutation
|
✅ Property access and mutation
|
||||||
✅ Method invocation
|
✅ Method invocation
|
||||||
✅ Constructor handling
|
✅ Constructor handling
|
||||||
✅ Type introspection
|
✅ Type introspection
|
||||||
✅ Basic metadata support
|
✅ Basic metadata support
|
||||||
✅ Error handling
|
✅ Comprehensive error handling
|
||||||
✅ Cross-platform support
|
✅ Cross-platform support (VM, Web, Flutter, AOT)
|
||||||
|
✅ Basic generic type support
|
||||||
|
✅ Library reflection
|
||||||
|
|
||||||
### Known Limitations
|
### Known Limitations
|
||||||
❌ No cross-isolate reflection
|
❌ Limited support for complex generic types
|
||||||
❌ Limited generic support
|
|
||||||
❌ No source location tracking
|
|
||||||
❌ No extension method support
|
❌ No extension method support
|
||||||
❌ No mixin composition
|
|
||||||
❌ Limited metadata capabilities
|
❌ Limited metadata capabilities
|
||||||
❌ No dynamic proxy generation
|
❌ No dynamic proxy generation
|
||||||
❌ No attribute-based reflection
|
❌ No reflection on private members
|
||||||
|
|
||||||
## Short-term Goals (v0.2.0)
|
## Short-term Goals (v0.2.0)
|
||||||
|
|
||||||
### 1. Enhanced Generic Support
|
### 1. Enhanced Generic Support
|
||||||
- [ ] Better generic type handling
|
- [ ] Improved handling of complex generic types
|
||||||
- [ ] Generic type argument preservation
|
- [ ] Support for generic methods and constructors
|
||||||
- [ ] Generic method support
|
- [ ] Type parameter bounds and variance
|
||||||
- [ ] Generic constructor support
|
|
||||||
- [ ] Type parameter constraints
|
|
||||||
|
|
||||||
### 2. Improved Type System
|
### 2. Improved Type System
|
||||||
- [ ] Better type relationship checking
|
- [ ] Enhanced type relationship checking
|
||||||
- [ ] Variance handling
|
- [ ] Better support for interfaces and mixins
|
||||||
- [ ] Type erasure handling
|
- [ ] Improved handling of type aliases
|
||||||
- [ ] Generic type instantiation
|
|
||||||
- [ ] Type parameter bounds
|
|
||||||
|
|
||||||
### 3. Metadata Enhancements
|
### 3. Metadata Enhancements
|
||||||
- [ ] Rich metadata API
|
- [ ] Rich metadata API for custom annotations
|
||||||
- [ ] Metadata inheritance
|
- [ ] Improved retrieval and manipulation of metadata
|
||||||
- [ ] Custom metadata providers
|
|
||||||
- [ ] Metadata validation
|
|
||||||
- [ ] Compile-time metadata
|
|
||||||
|
|
||||||
### 4. Performance Optimizations
|
### 4. Performance Optimizations
|
||||||
- [ ] Faster lookup mechanisms
|
- [ ] Further optimized lookup mechanisms
|
||||||
- [ ] Better memory usage
|
- [ ] Enhanced caching strategies
|
||||||
- [ ] Optimized registration
|
- [ ] Benchmarking and performance tuning
|
||||||
- [ ] Improved caching
|
|
||||||
- [ ] Reduced startup time
|
|
||||||
|
|
||||||
## Medium-term Goals (v0.3.0)
|
## Medium-term Goals (v0.3.0)
|
||||||
|
|
||||||
### 1. Dynamic Features
|
### 1. Advanced Type Features
|
||||||
- [ ] Dynamic proxy generation
|
- [ ] Support for extension methods
|
||||||
- [ ] Method interception
|
- [ ] Improved mixin composition handling
|
||||||
- [ ] Property interception
|
- [ ] Better support for sealed classes and enums
|
||||||
- [ ] Dynamic interface implementation
|
|
||||||
- [ ] Runtime mixin application
|
|
||||||
|
|
||||||
### 2. Advanced Type Features
|
### 2. Framework Integration
|
||||||
- [ ] Extension method support
|
- [ ] Deeper Flutter integration
|
||||||
- [ ] Operator overloading
|
- [ ] Built-in support for common serialization formats (JSON, protobuf)
|
||||||
- [ ] Mixin composition
|
- [ ] Integration with popular state management solutions
|
||||||
- [ ] Type alias support
|
|
||||||
- [ ] Named constructor factories
|
|
||||||
|
|
||||||
### 3. Tooling Support
|
### 3. Tooling and Developer Experience
|
||||||
- [ ] VS Code extension
|
- [ ] VS Code extension for easier registration and usage
|
||||||
- [ ] Dart analyzer plugin
|
- [ ] Dart analyzer plugin for static analysis
|
||||||
- [ ] Documentation generator
|
- [ ] Code generation tools to automate registration
|
||||||
- [ ] Migration tools
|
|
||||||
- [ ] Debug tools
|
|
||||||
|
|
||||||
### 4. Framework Integration
|
|
||||||
- [ ] Flutter integration
|
|
||||||
- [ ] Built Value integration
|
|
||||||
- [ ] JSON serialization
|
|
||||||
- [ ] Database mapping
|
|
||||||
- [ ] Dependency injection
|
|
||||||
|
|
||||||
## Long-term Goals (v1.0.0)
|
## Long-term Goals (v1.0.0)
|
||||||
|
|
||||||
### 1. Advanced Reflection
|
### 1. Advanced Reflection Capabilities
|
||||||
- [ ] Cross-isolate reflection
|
- [ ] Dynamic proxy generation
|
||||||
- [ ] Source location tracking
|
- [ ] Method interception and AOP-like features
|
||||||
- [ ] Dynamic loading
|
- [ ] Limited support for reflecting on private members (with security considerations)
|
||||||
- [ ] Code generation
|
|
||||||
- [ ] Hot reload support
|
|
||||||
|
|
||||||
### 2. Language Features
|
### 2. Language Feature Parity
|
||||||
- [ ] Pattern matching
|
- [ ] Full support for all Dart language features
|
||||||
- [ ] Records support
|
- [ ] Reflection capabilities for upcoming Dart features
|
||||||
- [ ] Sealed classes
|
|
||||||
- [ ] Enhanced enums
|
|
||||||
- [ ] Extension types
|
|
||||||
|
|
||||||
### 3. Enterprise Features
|
### 3. Enterprise and Framework Features
|
||||||
- [ ] Aspect-oriented programming
|
- [ ] Built-in dependency injection framework
|
||||||
- [ ] Dependency injection
|
- [ ] Advanced validation and serialization capabilities
|
||||||
- [ ] Object-relational mapping
|
- [ ] Integration with popular backend frameworks
|
||||||
- [ ] Serialization framework
|
|
||||||
- [ ] Validation framework
|
|
||||||
|
|
||||||
### 4. Security Features
|
|
||||||
- [ ] Access control
|
|
||||||
- [ ] Reflection policies
|
|
||||||
- [ ] Sandboxing
|
|
||||||
- [ ] Audit logging
|
|
||||||
- [ ] Security annotations
|
|
||||||
|
|
||||||
## Implementation Priorities
|
## Implementation Priorities
|
||||||
|
|
||||||
### Phase 1: Foundation (Current)
|
### Phase 1: Stabilization and Enhancement (Current)
|
||||||
1. Core reflection system
|
1. Improve generic type support
|
||||||
2. Basic type support
|
2. Enhance performance and optimize caching
|
||||||
3. Essential operations
|
3. Expand test coverage
|
||||||
4. Error handling
|
4. Improve documentation and examples
|
||||||
5. Documentation
|
|
||||||
|
|
||||||
### Phase 2: Enhancement (Next)
|
### Phase 2: Advanced Features and Integrations
|
||||||
1. Generic support
|
1. Implement advanced type system features
|
||||||
2. Type system improvements
|
2. Develop framework integrations
|
||||||
3. Metadata enhancements
|
3. Create developer tools and plugins
|
||||||
4. Performance optimizations
|
4. Enhance metadata capabilities
|
||||||
5. Framework integration
|
|
||||||
|
|
||||||
### Phase 3: Advanced Features
|
### Phase 3: Towards 1.0
|
||||||
1. Dynamic capabilities
|
1. Implement dynamic capabilities (proxies, interception)
|
||||||
2. Language feature support
|
2. Ensure full language feature support
|
||||||
3. Tooling integration
|
3. Develop enterprise-level features
|
||||||
4. Security features
|
4. Final API stabilization and performance tuning
|
||||||
5. Enterprise features
|
|
||||||
|
|
||||||
## Breaking Changes
|
## Breaking Changes
|
||||||
|
|
||||||
### Planned for v0.2.0
|
### Potential for v0.2.0
|
||||||
- API refinements for generic support
|
- API refinements for improved generic support
|
||||||
- Enhanced metadata system
|
- Enhancements to the registration process for better type information
|
||||||
- Improved type handling
|
|
||||||
- Registration system updates
|
|
||||||
|
|
||||||
### Planned for v0.3.0
|
### Potential for v0.3.0
|
||||||
- Dynamic proxy API
|
- Changes to support advanced type features
|
||||||
- Advanced type features
|
- Modifications to accommodate deeper framework integrations
|
||||||
- Framework integration APIs
|
|
||||||
- Security system
|
|
||||||
|
|
||||||
### Planned for v1.0.0
|
### For v1.0.0
|
||||||
- Stable API finalization
|
- Final API stabilization
|
||||||
- Enterprise feature integration
|
- Any necessary changes to support full language feature parity
|
||||||
- Cross-isolate capabilities
|
|
||||||
- Advanced language features
|
|
||||||
|
|
||||||
## Migration Support
|
## Community Feedback Focus
|
||||||
|
|
||||||
### For Each Major Version
|
1. Generic type handling and edge cases
|
||||||
- Migration guides
|
2. Performance in real-world scenarios
|
||||||
- Breaking change documentation
|
3. Integration pain points with popular frameworks
|
||||||
- Upgrade tools
|
4. API ergonomics and ease of use
|
||||||
- Code modification scripts
|
5. Documentation clarity and completeness
|
||||||
- Support period
|
|
||||||
|
|
||||||
## Community Feedback Areas
|
|
||||||
|
|
||||||
### Current Focus
|
|
||||||
1. Generic type handling
|
|
||||||
2. Performance optimization
|
|
||||||
3. Framework integration
|
|
||||||
4. API usability
|
|
||||||
5. Documentation quality
|
|
||||||
|
|
||||||
### Future Considerations
|
|
||||||
1. Enterprise features
|
|
||||||
2. Security requirements
|
|
||||||
3. Framework support
|
|
||||||
4. Language feature support
|
|
||||||
5. Tool integration
|
|
||||||
|
|
||||||
## Development Process
|
## Development Process
|
||||||
|
|
||||||
### 1. Feature Development
|
### Feature Development Workflow
|
||||||
```mermaid
|
1. Community proposal and discussion
|
||||||
graph LR
|
2. Design and API draft
|
||||||
A[Proposal] --> B[Design]
|
3. Implementation and internal testing
|
||||||
B --> C[Implementation]
|
4. Community feedback and iteration
|
||||||
C --> D[Testing]
|
5. Documentation and example creation
|
||||||
D --> E[Documentation]
|
6. Release and announcement
|
||||||
E --> F[Release]
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Release Cycle
|
### Release Cycle
|
||||||
- Major versions: Significant features/breaking changes
|
- Major versions: Significant features/breaking changes (roughly annually)
|
||||||
- Minor versions: New features/non-breaking changes
|
- Minor versions: New features/non-breaking changes (every 2-3 months)
|
||||||
- Patch versions: Bug fixes/performance improvements
|
- Patch versions: Bug fixes/performance improvements (as needed)
|
||||||
|
|
||||||
### 3. Testing Strategy
|
### Testing Strategy
|
||||||
- Unit tests
|
- Comprehensive unit test suite
|
||||||
- Integration tests
|
- Integration tests with popular frameworks
|
||||||
- Performance tests
|
- Performance benchmarks against dart:mirrors and direct code
|
||||||
- Platform compatibility tests
|
- Cross-platform compatibility tests
|
||||||
- Framework integration tests
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
### Priority Areas
|
### Priority Areas for Contribution
|
||||||
1. Generic type support
|
1. Generic type edge cases and improvements
|
||||||
2. Performance improvements
|
2. Performance optimizations and benchmarks
|
||||||
3. Framework integration
|
3. Framework integration examples and utilities
|
||||||
4. Documentation
|
4. Documentation improvements and tutorials
|
||||||
5. Testing
|
5. Test coverage expansion
|
||||||
|
|
||||||
### Getting Started
|
### Getting Started with Contributions
|
||||||
1. Review current limitations
|
1. Review the current limitations and roadmap
|
||||||
2. Check roadmap priorities
|
2. Check the issue tracker for "good first issue" labels
|
||||||
3. Read contribution guidelines
|
3. Read the CONTRIBUTING.md guidelines
|
||||||
4. Submit proposals
|
4. Engage in discussions on open issues or create a new one
|
||||||
5. Implement features
|
5. Submit pull requests with improvements or new features
|
||||||
|
|
||||||
## Support
|
## Tentative Timeline
|
||||||
|
|
||||||
### Long-term Support (LTS)
|
|
||||||
- v1.0.0 and later
|
|
||||||
- Security updates
|
|
||||||
- Critical bug fixes
|
|
||||||
- Performance improvements
|
|
||||||
- Documentation updates
|
|
||||||
|
|
||||||
### Version Support Matrix
|
|
||||||
| Version | Status | Support Until |
|
|
||||||
|---------|---------|--------------|
|
|
||||||
| 0.1.x | Current | 6 months |
|
|
||||||
| 0.2.x | Planned | 1 year |
|
|
||||||
| 0.3.x | Planned | 1 year |
|
|
||||||
| 1.0.x | Planned | 2 years |
|
|
||||||
|
|
||||||
## Success Metrics
|
|
||||||
|
|
||||||
### Technical Metrics
|
|
||||||
- Performance benchmarks
|
|
||||||
- Memory usage
|
|
||||||
- API coverage
|
|
||||||
- Test coverage
|
|
||||||
- Documentation coverage
|
|
||||||
|
|
||||||
### Community Metrics
|
|
||||||
- Adoption rate
|
|
||||||
- Issue resolution time
|
|
||||||
- Community contributions
|
|
||||||
- User satisfaction
|
|
||||||
- Framework adoption
|
|
||||||
|
|
||||||
## Get Involved
|
|
||||||
|
|
||||||
### Ways to Contribute
|
|
||||||
1. Submit bug reports
|
|
||||||
2. Propose features
|
|
||||||
3. Improve documentation
|
|
||||||
4. Add test cases
|
|
||||||
5. Implement features
|
|
||||||
|
|
||||||
### Communication Channels
|
|
||||||
- GitHub Issues
|
|
||||||
- Pull Requests
|
|
||||||
- Discord Server
|
|
||||||
- Stack Overflow
|
|
||||||
- Email Support
|
|
||||||
|
|
||||||
## Timeline
|
|
||||||
|
|
||||||
### 2024 Q1-Q2
|
### 2024 Q1-Q2
|
||||||
- Enhanced generic support
|
- Release v0.2.0 with enhanced generic support and performance improvements
|
||||||
- Improved type system
|
- Expand framework integration examples
|
||||||
- Performance optimizations
|
- Implement initial tooling support
|
||||||
- Documentation improvements
|
|
||||||
|
|
||||||
### 2024 Q3-Q4
|
### 2024 Q3-Q4
|
||||||
- Dynamic features
|
- Release v0.3.0 with advanced type features and deeper framework integrations
|
||||||
- Framework integration
|
- Develop and release initial VS Code extension and analyzer plugin
|
||||||
- Tool support
|
|
||||||
- Security features
|
|
||||||
|
|
||||||
### 2025
|
### 2025
|
||||||
- Cross-isolate reflection
|
- Implement dynamic proxy generation and method interception
|
||||||
- Enterprise features
|
- Finalize API for 1.0.0 release
|
||||||
- Language feature support
|
- Develop enterprise-level features and integrations
|
||||||
- 1.0.0 release
|
|
||||||
|
|
||||||
Note: This roadmap is subject to change based on community feedback and evolving requirements.
|
Note: This roadmap is subject to change based on community feedback, emerging requirements, and developments in the Dart ecosystem.
|
||||||
|
|
|
@ -6,64 +6,71 @@
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
graph TD
|
graph TD
|
||||||
A[Reflector] --> B[Scanner]
|
A[Reflector] --> B[RuntimeReflector]
|
||||||
A --> C[RuntimeReflector]
|
B --> C[MirrorSystem]
|
||||||
B --> D[TypeAnalyzer]
|
C --> D[Mirrors]
|
||||||
C --> E[MirrorSystem]
|
D --> E[ClassMirror]
|
||||||
E --> F[Mirrors]
|
D --> F[InstanceMirror]
|
||||||
F --> G[ClassMirror]
|
D --> G[MethodMirror]
|
||||||
F --> H[InstanceMirror]
|
D --> H[VariableMirror]
|
||||||
F --> I[MethodMirror]
|
D --> I[LibraryMirror]
|
||||||
|
D --> J[TypeMirror]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Component Responsibilities
|
### Component Responsibilities
|
||||||
|
|
||||||
#### 1. Reflector
|
#### 1. Reflector
|
||||||
- Central registration point
|
- Static class for central registration and metadata management
|
||||||
- Metadata management
|
|
||||||
- Type registration validation
|
- Type registration validation
|
||||||
- Cache management
|
- Metadata storage for properties, methods, and constructors
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
class Reflector {
|
class Reflector {
|
||||||
static final Map<Type, TypeMetadata> _typeCache;
|
static void register(Type type);
|
||||||
static final Map<Type, Map<String, PropertyMetadata>> _propertyMetadata;
|
static void registerProperty(Type type, String name, Type propertyType, {bool isWritable = true});
|
||||||
static final Map<Type, Map<String, MethodMetadata>> _methodMetadata;
|
static void registerMethod(Type type, String name, List<Type> parameterTypes, bool returnsVoid);
|
||||||
static final Map<Type, List<ConstructorMetadata>> _constructorMetadata;
|
static void registerConstructor(Type type, String name, {List<Type>? parameterTypes, List<String>? parameterNames, List<bool>? isRequired, List<bool>? isNamed, Function? creator});
|
||||||
|
static bool isReflectable(Type type);
|
||||||
|
static Map<String, PropertyMetadata>? getPropertyMetadata(Type type);
|
||||||
|
static Map<String, MethodMetadata>? getMethodMetadata(Type type);
|
||||||
|
static List<ConstructorMetadata>? getConstructorMetadata(Type type);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 2. Scanner
|
#### 2. RuntimeReflector
|
||||||
- Type analysis
|
- Singleton class for runtime reflection operations
|
||||||
- Metadata extraction
|
- Instance creation and manipulation
|
||||||
- Registration validation
|
- Type and class reflection
|
||||||
- Type relationship analysis
|
- Library reflection
|
||||||
|
|
||||||
```dart
|
|
||||||
class Scanner {
|
|
||||||
static final Map<Type, TypeInfo> _typeInfoCache;
|
|
||||||
|
|
||||||
static TypeInfo analyze(Type type) {
|
|
||||||
// Analyze class structure
|
|
||||||
// Extract metadata
|
|
||||||
// Build type relationships
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 3. RuntimeReflector
|
|
||||||
- Instance creation
|
|
||||||
- Method invocation
|
|
||||||
- Property access
|
|
||||||
- Type reflection
|
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
class RuntimeReflector {
|
class RuntimeReflector {
|
||||||
InstanceMirror reflect(Object object) {
|
static final RuntimeReflector instance = RuntimeReflector._();
|
||||||
// Create instance mirror
|
|
||||||
// Setup metadata access
|
InstanceMirror reflect(Object object);
|
||||||
// Configure invocation handling
|
ClassMirror reflectClass(Type type);
|
||||||
}
|
TypeMirror reflectType(Type type);
|
||||||
|
LibraryMirror reflectLibrary(Uri uri);
|
||||||
|
|
||||||
|
InstanceMirror createInstance(Type type, {List<dynamic>? positionalArgs, Map<Symbol, dynamic>? namedArgs, String? constructorName});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. MirrorSystem
|
||||||
|
- Manages the overall reflection system
|
||||||
|
- Provides access to libraries and types
|
||||||
|
- Handles special types (dynamic, void, never)
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class MirrorSystem implements MirrorSystemContract {
|
||||||
|
static MirrorSystem get instance;
|
||||||
|
static MirrorSystem current();
|
||||||
|
|
||||||
|
Map<Uri, LibraryMirrorContract> get libraries;
|
||||||
|
LibraryMirrorContract findLibrary(Symbol libraryName);
|
||||||
|
ClassMirrorContract reflectClass(Type type);
|
||||||
|
TypeMirrorContract reflectType(Type type);
|
||||||
|
IsolateMirrorContract get isolate;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -77,8 +84,8 @@ class TypeMetadata {
|
||||||
final Map<String, PropertyMetadata> properties;
|
final Map<String, PropertyMetadata> properties;
|
||||||
final Map<String, MethodMetadata> methods;
|
final Map<String, MethodMetadata> methods;
|
||||||
final List<ConstructorMetadata> constructors;
|
final List<ConstructorMetadata> constructors;
|
||||||
final bool isAbstract;
|
final TypeMetadata? supertype;
|
||||||
final bool isEnum;
|
final List<TypeMetadata> interfaces;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -89,8 +96,8 @@ class MethodMetadata {
|
||||||
final List<Type> parameterTypes;
|
final List<Type> parameterTypes;
|
||||||
final List<ParameterMetadata> parameters;
|
final List<ParameterMetadata> parameters;
|
||||||
final bool returnsVoid;
|
final bool returnsVoid;
|
||||||
|
final Type returnType;
|
||||||
final bool isStatic;
|
final bool isStatic;
|
||||||
final bool isAbstract;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -101,7 +108,6 @@ class PropertyMetadata {
|
||||||
final Type type;
|
final Type type;
|
||||||
final bool isReadable;
|
final bool isReadable;
|
||||||
final bool isWritable;
|
final bool isWritable;
|
||||||
final bool isStatic;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -112,20 +118,11 @@ class PropertyMetadata {
|
||||||
1. Type Registration
|
1. Type Registration
|
||||||
```dart
|
```dart
|
||||||
static void register(Type type) {
|
static void register(Type type) {
|
||||||
// Validate type
|
_reflectableTypes.add(type);
|
||||||
if (_typeCache.containsKey(type)) return;
|
_propertyMetadata.putIfAbsent(type, () => {});
|
||||||
|
_methodMetadata.putIfAbsent(type, () => {});
|
||||||
// Create metadata
|
_constructorMetadata.putIfAbsent(type, () => []);
|
||||||
final metadata = TypeMetadata(
|
_instanceCreators.putIfAbsent(type, () => {});
|
||||||
type: type,
|
|
||||||
name: type.toString(),
|
|
||||||
properties: {},
|
|
||||||
methods: {},
|
|
||||||
constructors: [],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Cache metadata
|
|
||||||
_typeCache[type] = metadata;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -138,23 +135,16 @@ static void registerProperty(
|
||||||
bool isReadable = true,
|
bool isReadable = true,
|
||||||
bool isWritable = true,
|
bool isWritable = true,
|
||||||
}) {
|
}) {
|
||||||
// Validate type registration
|
registerPropertyMetadata(
|
||||||
if (!isRegistered(type)) {
|
type,
|
||||||
throw NotReflectableException(type);
|
name,
|
||||||
}
|
PropertyMetadata(
|
||||||
|
|
||||||
// Create property metadata
|
|
||||||
final metadata = PropertyMetadata(
|
|
||||||
name: name,
|
name: name,
|
||||||
type: propertyType,
|
type: propertyType,
|
||||||
isReadable: isReadable,
|
isReadable: isReadable,
|
||||||
isWritable: isWritable,
|
isWritable: isWritable,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Cache metadata
|
|
||||||
_propertyMetadata
|
|
||||||
.putIfAbsent(type, () => {})
|
|
||||||
[name] = metadata;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -165,30 +155,13 @@ static void registerMethod(
|
||||||
String name,
|
String name,
|
||||||
List<Type> parameterTypes,
|
List<Type> parameterTypes,
|
||||||
bool returnsVoid, {
|
bool returnsVoid, {
|
||||||
|
Type? returnType,
|
||||||
List<String>? parameterNames,
|
List<String>? parameterNames,
|
||||||
List<bool>? isRequired,
|
List<bool>? isRequired,
|
||||||
|
List<bool>? isNamed,
|
||||||
|
bool isStatic = false,
|
||||||
}) {
|
}) {
|
||||||
// Validate type registration
|
// Implementation details...
|
||||||
if (!isRegistered(type)) {
|
|
||||||
throw NotReflectableException(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create method metadata
|
|
||||||
final metadata = MethodMetadata(
|
|
||||||
name: name,
|
|
||||||
parameterTypes: parameterTypes,
|
|
||||||
parameters: _createParameters(
|
|
||||||
parameterTypes,
|
|
||||||
parameterNames,
|
|
||||||
isRequired,
|
|
||||||
),
|
|
||||||
returnsVoid: returnsVoid,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Cache metadata
|
|
||||||
_methodMetadata
|
|
||||||
.putIfAbsent(type, () => {})
|
|
||||||
[name] = metadata;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -201,203 +174,76 @@ InstanceMirror createInstance(
|
||||||
Map<Symbol, dynamic>? namedArgs,
|
Map<Symbol, dynamic>? namedArgs,
|
||||||
String? constructorName,
|
String? constructorName,
|
||||||
}) {
|
}) {
|
||||||
// Get constructor metadata
|
// Implementation details...
|
||||||
final constructors = Reflector.getConstructorMetadata(type);
|
|
||||||
if (constructors == null) {
|
|
||||||
throw ReflectionException('No constructors found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find matching constructor
|
|
||||||
final constructor = constructors.firstWhere(
|
|
||||||
(c) => c.name == (constructorName ?? ''),
|
|
||||||
orElse: () => throw ReflectionException('Constructor not found'),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Validate arguments
|
|
||||||
_validateArguments(
|
|
||||||
constructor,
|
|
||||||
positionalArgs,
|
|
||||||
namedArgs,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Create instance
|
|
||||||
final instance = constructor.creator!(
|
|
||||||
positionalArgs,
|
|
||||||
namedArgs,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Return mirror
|
|
||||||
return InstanceMirror(
|
|
||||||
instance,
|
|
||||||
type,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Method Invocation
|
### Method Invocation
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
InstanceMirror invoke(
|
InstanceMirror invoke(Symbol methodName, List<dynamic> positionalArguments, [Map<Symbol, dynamic>? namedArguments]) {
|
||||||
Symbol methodName,
|
// Implementation details...
|
||||||
List<dynamic> positionalArguments, [
|
|
||||||
Map<Symbol, dynamic>? namedArguments,
|
|
||||||
]) {
|
|
||||||
// Get method metadata
|
|
||||||
final method = _getMethodMetadata(methodName);
|
|
||||||
if (method == null) {
|
|
||||||
throw ReflectionException('Method not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate arguments
|
|
||||||
_validateMethodArguments(
|
|
||||||
method,
|
|
||||||
positionalArguments,
|
|
||||||
namedArguments,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Invoke method
|
|
||||||
final result = method.invoke(
|
|
||||||
instance,
|
|
||||||
positionalArguments,
|
|
||||||
namedArguments,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Return result mirror
|
|
||||||
return InstanceMirror(
|
|
||||||
result,
|
|
||||||
result.runtimeType,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Performance Optimizations
|
## Performance Optimizations
|
||||||
|
|
||||||
### 1. Metadata Caching
|
- Metadata caching on registration for fast lookup
|
||||||
- Type metadata cached on registration
|
- Use of HashMap for O(1) average case lookups
|
||||||
- Method metadata cached on registration
|
- Lazy initialization of certain components (e.g., special types in MirrorSystem)
|
||||||
- Property metadata cached on registration
|
- Reuse of mirrors for repeated operations on the same object
|
||||||
|
|
||||||
### 2. Lookup Optimization
|
|
||||||
- O(1) type lookup
|
|
||||||
- O(1) method lookup
|
|
||||||
- O(1) property lookup
|
|
||||||
|
|
||||||
### 3. Memory Management
|
|
||||||
- Weak references for type cache
|
|
||||||
- Lazy initialization of metadata
|
|
||||||
- Minimal metadata storage
|
|
||||||
|
|
||||||
## Error Handling
|
## Error Handling
|
||||||
|
|
||||||
### Exception Hierarchy
|
|
||||||
```dart
|
```dart
|
||||||
abstract class ReflectionException implements Exception {
|
class ReflectionException implements Exception {
|
||||||
final String message;
|
final String message;
|
||||||
final StackTrace? stackTrace;
|
ReflectionException(this.message);
|
||||||
|
@override
|
||||||
|
String toString() => 'ReflectionException: $message';
|
||||||
}
|
}
|
||||||
|
|
||||||
class NotReflectableException extends ReflectionException {
|
class NotReflectableException extends ReflectionException {
|
||||||
final Type type;
|
NotReflectableException(Type type) : super('Type is not reflectable: $type');
|
||||||
}
|
}
|
||||||
|
|
||||||
class InvalidArgumentsException extends ReflectionException {
|
class InvalidArgumentsException extends ReflectionException {
|
||||||
final String memberName;
|
InvalidArgumentsException(String message, Type type) : super(message);
|
||||||
final Type type;
|
|
||||||
}
|
|
||||||
|
|
||||||
class MemberNotFoundException extends ReflectionException {
|
|
||||||
final String memberName;
|
|
||||||
final Type type;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Validation Points
|
|
||||||
1. Registration validation
|
|
||||||
2. Argument validation
|
|
||||||
3. Type validation
|
|
||||||
4. Access validation
|
|
||||||
|
|
||||||
## Platform Considerations
|
## Platform Considerations
|
||||||
|
|
||||||
### Web Support
|
- Full support for VM, Web, Flutter, and AOT compilation
|
||||||
- No dart:mirrors dependency
|
- No use of dart:mirrors, ensuring cross-platform compatibility
|
||||||
- Tree-shaking friendly
|
- Explicit registration allows for better tree-shaking and smaller code size
|
||||||
- Minimal runtime overhead
|
|
||||||
|
|
||||||
### Flutter Support
|
|
||||||
- AOT compilation compatible
|
|
||||||
- No code generation required
|
|
||||||
- Performance optimized
|
|
||||||
|
|
||||||
### Native Support
|
|
||||||
- Cross-platform compatible
|
|
||||||
- No platform-specific code
|
|
||||||
- Consistent behavior
|
|
||||||
|
|
||||||
## Limitations and Constraints
|
## Limitations and Constraints
|
||||||
|
|
||||||
### Technical Limitations
|
- Explicit registration required for all reflectable types and members
|
||||||
1. No cross-isolate reflection
|
- Limited support for complex generic types
|
||||||
2. No source location support
|
- No reflection on private members
|
||||||
3. Limited generic support
|
- No dynamic loading of code or types at runtime
|
||||||
4. No extension method support
|
|
||||||
|
|
||||||
### Design Decisions
|
|
||||||
1. Explicit registration required
|
|
||||||
2. No private member access
|
|
||||||
3. No dynamic loading
|
|
||||||
4. No proxy generation
|
|
||||||
|
|
||||||
## Future Considerations
|
## Future Considerations
|
||||||
|
|
||||||
### Planned Improvements
|
- Enhanced generic type support, including variance and type parameter bounds
|
||||||
1. Enhanced generic support
|
- Improved metadata capabilities, including custom metadata providers
|
||||||
2. Better type relationship handling
|
- Dynamic proxy generation for more advanced use cases
|
||||||
3. Improved metadata capabilities
|
- Potential for code generation tools to automate registration process
|
||||||
4. Performance optimizations
|
|
||||||
|
|
||||||
### Potential Features
|
|
||||||
1. Attribute-based reflection
|
|
||||||
2. Dynamic proxy generation
|
|
||||||
3. Enhanced type analysis
|
|
||||||
4. Improved error reporting
|
|
||||||
|
|
||||||
## Security Considerations
|
## Security Considerations
|
||||||
|
|
||||||
### Access Control
|
- No access to private members, maintaining encapsulation
|
||||||
- No private member access
|
- Controlled reflection surface through explicit registration
|
||||||
- Controlled reflection surface
|
- Runtime type checking and validation during reflection operations
|
||||||
- Explicit registration required
|
|
||||||
|
|
||||||
### Type Safety
|
|
||||||
- Strong type checking
|
|
||||||
- Runtime validation
|
|
||||||
- Safe method invocation
|
|
||||||
|
|
||||||
## Testing Strategy
|
## Testing Strategy
|
||||||
|
|
||||||
### Unit Tests
|
- Comprehensive unit tests for all core components (Reflector, RuntimeReflector, MirrorSystem)
|
||||||
1. Registration tests
|
- Integration tests simulating real-world usage scenarios
|
||||||
2. Reflection tests
|
- Performance benchmarks comparing against direct method calls and dart:mirrors (where applicable)
|
||||||
3. Error handling tests
|
- Cross-platform tests ensuring consistent behavior across VM, Web, and Flutter
|
||||||
4. Performance tests
|
- Stress tests with large numbers of registered types and reflection operations
|
||||||
|
|
||||||
### Integration Tests
|
This technical specification provides a detailed overview of the Platform Reflection library's architecture, implementation details, and key considerations. For API documentation and usage examples, please refer to the [README](../README.md) and [Quick Start Guide](quick_start.md).
|
||||||
1. Platform compatibility
|
|
||||||
2. Framework integration
|
|
||||||
3. Real-world scenarios
|
|
||||||
4. Edge cases
|
|
||||||
|
|
||||||
## Documentation Requirements
|
|
||||||
|
|
||||||
### API Documentation
|
|
||||||
1. Public API documentation
|
|
||||||
2. Usage examples
|
|
||||||
3. Best practices
|
|
||||||
4. Migration guides
|
|
||||||
|
|
||||||
### Technical Documentation
|
|
||||||
1. Architecture overview
|
|
||||||
2. Implementation details
|
|
||||||
3. Performance considerations
|
|
||||||
4. Security guidelines
|
|
||||||
|
|
|
@ -310,17 +310,17 @@ class MirrorSystem implements MirrorSystemContract {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The current mirror system.
|
// /// The current mirror system.
|
||||||
MirrorSystemContract currentMirrorSystem() => MirrorSystem.current();
|
// MirrorSystemContract currentMirrorSystem() => MirrorSystem.current();
|
||||||
|
|
||||||
/// Reflects an instance.
|
// /// Reflects an instance.
|
||||||
InstanceMirrorContract reflect(Object reflectee) =>
|
// InstanceMirrorContract reflect(Object reflectee) =>
|
||||||
MirrorSystem.instance.reflect(reflectee);
|
// MirrorSystem.instance.reflect(reflectee);
|
||||||
|
|
||||||
/// Reflects a class.
|
// /// Reflects a class.
|
||||||
ClassMirrorContract reflectClass(Type key) =>
|
// ClassMirrorContract reflectClass(Type key) =>
|
||||||
MirrorSystem.instance.reflectClass(key);
|
// MirrorSystem.instance.reflectClass(key);
|
||||||
|
|
||||||
/// Reflects a type.
|
// /// Reflects a type.
|
||||||
TypeMirrorContract reflectType(Type key) =>
|
// TypeMirrorContract reflectType(Type key) =>
|
||||||
MirrorSystem.instance.reflectType(key);
|
// MirrorSystem.instance.reflectType(key);
|
||||||
|
|
Loading…
Reference in a new issue