Search code examples
dartdart-mirrors

Is it possible to get a class mirror by name?


Suppose I have defined a library app with some classes:

library app;

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

Is it possible to get the mirrors of class specified by name?

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

Solution

  • Here is possible example of your requirements.

    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 {}
    

    Output:

    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