我试图在这篇帖子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
飞镖队可能从classes
删除LibraryMirror
,有人知道其他选择吗?
我使用的是dart版本:1.24.3
答案 0 :(得分: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();
}
希望这可以帮助某人