Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Last active February 3, 2022 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hotdang-ca/d9648fa1c58c3487f490f13010b22aab to your computer and use it in GitHub Desktop.
Save hotdang-ca/d9648fa1c58c3487f490f13010b22aab to your computer and use it in GitHub Desktop.
Basic Object name via Reflection in Dart
import 'dart:mirrors';
class User {
final String email;
final String name;
const User({required this.email, required this.name});
}
extension DeclarationMirrorExtension on DeclarationMirror {
/// Name of this object or field
String get nameOf =>
RegExp(r'"(.*?)"').firstMatch(simpleName.toString())!.group(1).toString();
}
void main() {
print('All declared objects');
reflectClass(User).declarations.forEach((key, value) {
print(value.nameOf);
});
print('\nSpecific declared object');
print(reflectClass(User).declarations[#email]!.nameOf);
print('\nOn an object instance');
var user = User(email: 'james@hotdang.ca', name: 'James Perih');
print(reflect(user).type.nameOf);
print('\nOn an object instance field');
print(reflect(user).type.declarations[#email]!.nameOf);
print('\nValue through reflection');
print(reflect(user).getField(#email).reflectee);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment