在Dart中,给定一个Type名称,你如何获得Type(class)本身?

时间:2013-11-26 03:16:04

标签: dart dart-mirrors

如果有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的名称,如何从Typeclass获取Object,并知道如何实例化Type。缺少最后一块 - 你如何从它的名字派生Type

1 个答案:

答案 0 :(得分:3)

注意:镜像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