Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

how to invoke class form dart library string or file

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...