Last active
February 3, 2022 20:20
-
-
Save hotdang-ca/d9648fa1c58c3487f490f13010b22aab to your computer and use it in GitHub Desktop.
Basic Object name via Reflection in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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