Skip to content

Instantly share code, notes, and snippets.

@SwarmShepherd
Created November 3, 2012 01:58
Show Gist options
  • Save SwarmShepherd/4005492 to your computer and use it in GitHub Desktop.
Save SwarmShepherd/4005492 to your computer and use it in GitHub Desktop.
Example of using Reflection in Dart
#import('dart:mirrors');
class MyClass {
String _test;
String get test => _test;
set test(String paramVal) => _test = paramVal;
void my_method() {
}
void print_test(){
print("test string is: ${_test}");
}
MyClass(String test) {
_test = test;
}
}
main() {
MyClass myClass = new MyClass("Make my day, PUNK.");
myClass.print_test(); //>> Make my day, PUNK.
InstanceMirror myClassInstanceMirror = reflect(myClass);
ClassMirror MyClassMirror = myClassInstanceMirror.type;
Map<String, MethodMirror> map = MyClassMirror.methods;
print("map = ${map}");
//Output: map = {my_method: MethodMirror on 'my_method', print_test: MethodMirror on 'print_test'} test string is: Make my day
map.values.forEach( (MethodMirror mm){
myClassInstanceMirror.invoke(mm.simpleName,[]); //Will call the methods
});
}
@psygo
Copy link

psygo commented Sep 2, 2020

Save this as a .dart file so we can get proper syntax highlighting, please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment