【问题标题】:in Dart, given a Type name, how do you get the Type (class) itself? [duplicate]在 Dart 中,给定一个类型名称,如何获取类型(类)本身? [复制]
【发布时间】:2013-11-26 03:16:04
【问题描述】:

如果有Type,使用Mirrors可以得到Type的名字。反过来,给定Type 的名字,你如何得到Type

例如,来自以Dart 为中心的Angular 版本:

index.html

<form ng-controller='word?reset=true' >
 ...
</form>

mylib.dart

class Controller {
  Controller( Brando brando, Element elem, Map args ) { ... }
}
class Word extends Controller { ... }
class LangList extends Controller { ... }

// Brando, the godfather
class Brando {
  ...
  void compile( Element el ) {
    ...
    // add controller
    if( el.attributes.contains( 'ng-controller' ) {
      var name = el.attributes.getTypeName();  &lt;== "Word"
      var args = el.attributes.getTypeArgs();  &lt;== { 'reset': 'true' }
      var type = &lt;get type from camelized Type name&gt;  &lt;=== how??
      this.controllers.add( reflectClass(type).newInstance(
         const Symbol(''), [this,el,args]).reflectee );  &lt;=== instance from type
    }
    ...
  }
}

知道如何获取Type 的名称,如何从classObject 中获取Type,并知道如何实例化Type。缺少最后一块 - 你如何从它的名字中推导出 Type

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    注意:镜像 API 是“不稳定的”,所以这个答案可能会随着时间而改变。 *注意:这可能(将)使您生成的 javascript 膨胀,请参阅:https://api.dartlang.org/docs/channels/stable/latest/dart_mirrors/MirrorSystem.html#getSymbol*

    import 'dart:mirrors';
    class Bar {
    }
    
    ClassMirror findClassMirror(String name) {
      for (var lib in currentMirrorSystem().libraries.values) {
        var mirror = lib.declarations[MirrorSystem.getSymbol(name)];
        if (mirror != null) return mirror;
      }
      throw new ArgumentError("Class $name does not exist");
    }
    
    void main() {
      ClassMirror mirror = findClassMirror("Bar");
      print("mirror: $mirror");
    }
    

    输出:

    镜像:'Bar' 上的 ClassMirror

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多