You need to know the library name and class name to make things work properly. Assume you know both, the below example will instantiate the TestClass
and call doStuff
on it.
library test;
import "dart:mirrors";
class TestClass {
doStuff() => print("doStuff was called!");
}
main() {
MirrorSystem mirrors = currentMirrorSystem();
LibraryMirror lm = mirrors.libraries['test'];
ClassMirror cm = lm.classes['TestClass'];
Future tcFuture = cm.newInstance('', []);
tcFuture.then((InstanceMirror im) {
var tc = im.reflectee;
tc.doStuff();
});
}
A few notes about this solution:
- The library
test
we are trying to load the class from is already imported in the VM, which makes this case a bit easier.
- the call the
newInstance
allows for passing parameters to the constructor. Positional arguments are implemented, but named parameters are not yet implemented (as of the M2 release).
newInstance
returns a Future to allow it to work across isolates.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…