3

假设我定义了一个app包含一些类的库:

library app;

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

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

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

1 回答 1

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
于 2013-07-13T15:06:08.427 回答