Reflectable is a Dart

Reflectable is a Dart library that allows programmers to eliminate certain usages of dynamic reflection by specialization of reflective code to an equivalent implementation using only static techniques. The use of dynamic reflection is constrained in order to ensure that the specialized code can be generated and will have a reasonable size.


main.dart:


import 'package:reflectable/reflectable.dart';

import 'main.reflectable.dart'; // Import generated code.

// Annotate with this class to enable reflection.

class Reflector extends Reflectable {

  const Reflector()

      : super(invokingCapability); // Request the capability to invoke methods.

}

const reflector = const Reflector();

@reflector // This annotation enables reflection on A.

class A {

  final int a;

  A(this.a);

  greater(int x) => x > a;

  lessEqual(int x) => x <= a;

}

main() {

  initializeReflectable(); // Set up reflection support.

  A x = new A(10);

  // Reflect upon [x] using the const instance of the reflector:

  InstanceMirror instanceMirror = reflector.reflect(x);

  int weekday = new DateTime.now().weekday;

  // On Fridays we test if 3 is greater than 10, on other days if it is less

  // than or equal.

  String methodName = weekday == DateTime.FRIDAY ? "greater" : "lessEqual";

  // Reflectable invocation:

  print(instanceMirror.invoke(methodName, [3]));

}


Also You can invoke a static getter with reflectable like this;


import 'package:reflectable/reflectable.dart';

class Reflector extends Reflectable {

  const Reflector() : super(staticInvokeCapability);

}

const reflector = const Reflector();

@reflector

class ClassToReflect {

  static double staticPropertyToInvoke = 15;

}


Main.dart

import 'package:reflectable/reflectable.dart';

import 'main.reflectable.dart';

void main() {

  initializeReflectable();

  ClassMirror x = reflector.reflectType(ClassToReflect);

  var y = x.invokeGetter('staticPropertyToInvoke');

  debugPrint(y);

}


Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime