如果有Type
,使用Mirrors
可以获得Type
名称。相反,给定一个Type
的名称,你如何获得Type
?
例如,以Dart
为中心版Angular
:
<form ng-controller='word?reset=true' >
...
</form>
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(); <== "Word"
var args = el.attributes.getTypeArgs(); <== { 'reset': 'true' }
var type = <get type from camelized Type name> <=== how??
this.controllers.add( reflectClass(type).newInstance(
const Symbol(''), [this,el,args]).reflectee ); <=== instance from type
}
...
}
}
知道如何获取Type
的名称,如何从Type
和class
获取Object
,并知道如何实例化Type
。缺少最后一块 - 你如何从它的名字派生Type
?
答案 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