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

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

问题描述

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

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

例如:


  • 在javascript中的香草:

var myObject = window[classNameString];




  • Objective-C:



      • Objective-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 ,这使得这种情况有点更容易。

        2. 调用 newInstance 允许将参数传递给构造函数。位置参数已实现,但命名参数尚未实现(从M2版本开始)。

        3. newInstance 返回未来,以允许它在隔离区

        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天全站免登陆