如何调用类形式 dart 库字符串或文件 [英] how to invoke class form dart library string or file

查看:16
本文介绍了如何调用类形式 dart 库字符串或文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁来调用类表单 dart 库字符串或文件?

who to invoke class form dart library string or file?

例如

for-load.dart 文件

for-load.dart file

class TestLoad {
  void requestHandler(){
  }
}

然后是 main.dart 文件

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

谢谢!

推荐答案

这些符号是要动态调用的类的库、类和构造函数的名称

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

这篇关于如何调用类形式 dart 库字符串或文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆