是否可以通过名称获得类镜像?

时间:2013-07-13 14:34:32

标签: dart dart-mirrors

假设我已经使用某些类定义了库app

library app;

class User {
    // some members
}
class Question {}
class Answer {}

是否可以获取按名称指定的类的镜像?

var className = specifyClassName(); // may be "User", "Question", etc
ClassMirror cm = getClassMirror(className);

1 个答案:

答案 0 :(得分:4)

以下是您的要求的可能示例。

library app;

import 'dart:mirrors';
import 'dart:async';

void main() {
  var names = [
    'dart.async.Future',
    'dart.mirrors.ClassMirror',
    'app.User',
    'app.Question',
    'Answer',
    'app.Stackoverflow'
    ];

  for(var name in names) {
    var clazz = getClassMirrorByName(name);
    print('$name: $clazz');
  }
}

ClassMirror getClassMirrorByName(String className) {
  if(className == null) {
    return null;
  }

  var index = className.lastIndexOf('.');
  var libname = '';
  var name = className;
  if(index > 0) {
    libname = className.substring(0, index);
    name = className.substring(index + 1);
  }

  LibraryMirror lib;
  if(libname.isEmpty) {
    lib = currentMirrorSystem().isolate.rootLibrary;
  } else {
    var libs = currentMirrorSystem().findLibrary(new Symbol(libname)).toList();
    if(libs.length == 1) {
      lib = libs.first;
    }
  }

  if(lib == null) {
    return null;
  }

  return lib.classes[new Symbol(name)];
}

class User {
    // some members
}
class Question {}
class Answer {}

输出:

dart.async.Future: ClassMirror on 'Future'
dart.mirrors.ClassMirror: ClassMirror on 'ClassMirror'
app.User: ClassMirror on 'User'
app.Question: ClassMirror on 'Question'
Answer: ClassMirror on 'Answer'
app.Stackoverflow: null