1

if have a Type, using Mirrors can get the Type name. inversely, given a Type's name, how do you get the Type?

for example, from a Dart-centric version of 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
    }
    ...
  }
}

know how to get name of Type, how to get Type from class and Object, and know how to instantiate a Type. missing final piece - how do you derive the Type from its name?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
cc young
  • 18,939
  • 31
  • 90
  • 148

1 Answers1

3

Note: The mirror API is `unstable', so this answer may change over time. *Note: This may (will) bloat your generated javascript see: 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");
}

output:

mirror: ClassMirror on 'Bar'

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
jtmcdole
  • 566
  • 4
  • 8