从字符串实例化一个类 [英] Instantiate a class from a string

查看:37
本文介绍了从字符串实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 dart 中是否可以从字符串实例化一个类?

In dart is it possible to instantiate a class from a string?

例如:

  • javascript 中的香草:
var myObject = window[classNameString];

  • 目标-C:
  • id myclass = [[NSClassFromString(@"MyClass") alloc] init];
    

    推荐答案

    你需要知道库名和类名才能正常工作.假设您都知道,下面的示例将实例化 TestClass 并对其调用 doStuff.

    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:

    1. 我们试图从中加载类的库 test 已经导入到 VM 中,这使得这种情况更容易一些.
    2. 调用 newInstance 允许将参数传递给构造函数.实现了位置参数,但尚未实现命名参数(从 M2 版本开始).
    3. newInstance 返回一个 Future 到允许它跨隔离工作.
    1. The library test we are trying to load the class from is already imported in the VM, which makes this case a bit easier.
    2. 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).
    3. newInstance returns a Future to allow it to work across isolates.

    这篇关于从字符串实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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