reflection_factory 2.3.4 copy "reflection_factory: ^2.3.4" to clipboard
reflection_factory: ^2.3.4 copied to clipboard

Allows Dart reflection with an easy approach, even for third-party classes, using code generation portable for all Dart platforms.

example/reflection_factory_example.dart

import 'package:reflection_factory/reflection_factory.dart';

// Add a reference to the code generated by:
// $> dart run build_runner build
part 'reflection_factory_example.reflection.g.dart';

// Indicates that reflection for class `User` will be generated/enabled:
@EnableReflection()
class User {
  String? email;

  String pass;

  User(this.email, this.pass);

  User.empty() : this(null, '');

  bool get hasEmail => email != null;

  bool checkPassword(String pass) {
    return this.pass == pass;
  }
}

void main() {
  var user = User('joe@mail.com', '123');

  // The generated reflection:
  var userReflection = user.reflection;

  var fieldEmail = userReflection.field('email')!;
  print('email: ${fieldEmail.get()}');

  var methodCheckPassword = userReflection.method('checkPassword')!;

  var passOk1 = methodCheckPassword.invoke(['wrong']); // false
  print('pass("wrong"): $passOk1');

  var passOk2 = methodCheckPassword.invoke(['123']); // true
  print('pass("123"): $passOk2');

  // Using the generated `toJson` extension method:
  print('User JSON:');
  print(user.toJson());

  // Using the generated `toJsonEncoded` extension method:
  print('User JSON encoded:');
  print(user.toJsonEncoded());

  // Accessing reflection through class:
  var userReflection2 = User$reflection();

  // Creating an `User` instance from the default or empty constructor:
  var user2 = userReflection2.createInstance()!;

  user2.email = 'smith@mail.com';
  user2.pass = 'abc';

  print('User 2 JSON:');
  print(user2.toJson());
}

// ------------------------
// OUTPUT:
// ------------------------
// email: joe@mail.com
// pass("wrong"): false
// pass("123"): true
// User JSON:
// {email: joe@mail.com, hasEmail: true, pass: 123}
// User JSON encoded:
// {"email":"joe@mail.com","hasEmail":true,"pass":"123"}
// User 2 JSON:
// {email: smith@mail.com, hasEmail: true, pass: abc}
14
likes
140
pub points
79%
popularity

Publisher

unverified uploader

Allows Dart reflection with an easy approach, even for third-party classes, using code generation portable for all Dart platforms.

Repository (GitHub)
View/report issues

Documentation

API reference

License

Apache-2.0 (LICENSE)

Dependencies

analyzer, base_codecs, build, collection, dart_style, meta, mime, path, pub_semver, source_span, yaml

More

Packages that depend on reflection_factory