serverdartdart-mirrors

Get all subclasses in dart


I am trying to get all the subclasses of a given class following this post Find all subclasses in dart like this:

import 'dart:mirrors';
class A {}
class B extends A{}

List<Type> getSubclasses(Type type) {
    List<Type> subClasses = [];
    MirrorSystem mirrorSystem = currentMirrorSystem();

    // NoSuchMethodError: Class '_LocalLibraryMirror' has no instance getter 'classes'. ???
    mirrorSystem.isolate.rootLibrary.classes.forEach((s, c) {
        if (c.superclass == type) {
            subClasses.add(c);
        }
    });
    return subClasses;
}

main() {
    var result = getSubclasses(A);
    print(result);
}

But I am getting the following error:

Unhandled exception: NoSuchMethodError: Class '_LocalLibraryMirror' has no instance getter 'classes'. Receiver: Instance of '_LocalLibraryMirror' Tried calling: classes

The dart team probably removed that classes form the LibraryMirror, Does anybody knows any alternative?

I am using dart version: 1.24.3


Solution

  • Following Randal's suggestion, I could fix my problem with the following code:

    import 'dart:mirrors';
    
    List<ClassMirror> findSubClasses(Type type) {
        ClassMirror classMirror = reflectClass(type);
    
        return currentMirrorSystem()
            .libraries
            .values
            .expand((lib) => lib.declarations.values)
            .where((lib) {
                return lib is ClassMirror &&
                lib.isSubclassOf(classMirror) &&
                lib != classMirror;
            }).toList();
    }
    

    Hopefully this can help someone