9

我有三个飞镖课程:

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

1 回答 1

8

镜像库可以提供一些信息:

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
于 2013-04-22T22:02:30.397 回答