我在dart中有三个类:
class A {}
class B extends A{}
class C extends A{}
有一种方法得到所有子类从a ?
编辑:谢谢Alexandre Ardhuin你的解决方案工作完美!
我在学飞镖我编辑了你的代码,并把递归的解决方案,看看:
import 'dart:mirrors';
class A {}
class B extends A{}
class C extends A{}
class D {}
class E extends C {}
bool isParent(String parent,ClassMirror clazz){
var objectParentName = MirrorSystem.getName(clazz.superclass.simpleName);
if (objectParentName == "Object"){
return parent == "Object";
}
var result = parent == objectParentName;
if (!result){
return isParent(parent,clazz.superclass);
}
return result;
}
List<String> findAllSubclasses(String clazz){
var result = [];
final ms = currentMirrorSystem();
ms.isolate.rootLibrary.classes.forEach((s,c) {
if (isParent(clazz,c)){
result.add(MirrorSystem.getName(c.simpleName));
}
});
return result;
}
main(){
var result = findAllSubclasses('A');
print(result);
}
镜像库可以提供一些信息:
import 'dart:mirrors';
class A {}
class B extends A{}
class C extends A{}
class D {}
main(){
final ms = currentMirrorSystem();
ms.isolate.rootLibrary.classes.forEach((s,c) {
final parentClassName = MirrorSystem.getName(c.superclass.simpleName);
if (parentClassName == 'A') {
final className = MirrorSystem.getName(c.simpleName);
print('$className has A as super class');
}
});
}
输出将是:
C has A as super class
B has A as super class