how to invoke class form dart library string or file

浪子不回头ぞ 提交于 2019-11-26 21:52:49

问题


who to invoke class form dart library string or file?

for example

for-load.dart file

class TestLoad {
  void requestHandler(){
  }
}

then main.dart file

main(){
   //this get load lib
   var lib = currentMirrorSystem().libraries[Uri.parse('dart:core')];
   //who to invoke class form TestLoad or for-load.dart? 
   //like java Class.forName('TestLoad') , nodejs require('for-load')
}

thanks!


回答1:


These symbols are the names of the Library, the Class and the constructor for the Class that you want to dynamically invoke

foo.dart

library foo_library;

class Foo {
  String bar;
}

invoke_class.dart

library new_instance_test;

import "dart:mirrors";
import "foo.dart";

int main() {
  // These symbols are the names of the Library, the Class and the constructor for the Class that you want to dynamically load
  final Symbol librarySymbol = const Symbol("foo_library");
  final Symbol classSymbol = const Symbol("Foo");
  final Symbol constructorSymbol = const Symbol("");

  MirrorSystem mirrorSystem = currentMirrorSystem();

  // Get LibraryMirror for Library foo_library.
  // It returns an iterator, get the first LibraryMirror
  LibraryMirror libraryMirror = mirrorSystem.findLibrary(librarySymbol).first;

  // Get ClassMirror for Class Foo
  ClassMirror classMirror = libraryMirror.declarations[classSymbol];

  // Get the InstanceMirror using the default constructor
  InstanceMirror testClassInstanceMirror = classMirror.newInstance(constructorSymbol, []);

  //Get the reflectee object from the InstanceMirror
  Foo foo = testClassInstanceMirror.reflectee;

  //Set bar and print it
  foo.bar = "foobar";
  print(foo.bar);
}



回答2:


Something that could be quite useful for you, as mentioned in the comments, are isolates. If you want to take a look at them, you should look at this blogpost of Seth Ladd. I'll also dig into that topic and see if I can get things running.



来源:https://stackoverflow.com/questions/19166146/how-to-invoke-class-form-dart-library-string-or-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!