获取dart中的所有子类

Get all subclasses in dart

我正在尝试获取给定 class 的所有子 class,如下所示 post Find all subclasses in dart

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);
}

但我收到以下错误:

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

dart 团队可能从 LibraryMirror 中删除了 classes,有人知道其他替代方法吗?

我使用的是 dart 版本:1.24.3

按照 Randal 的建议,我可以使用以下代码解决我的问题:

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();
}

希望这可以帮助到某人