在dart中查找所有子类

时间:2013-04-22 15:05:53

标签: inheritance reflection dart dart-mirrors

我在飞镖中有三个课程:

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

2 个答案:

答案 0 :(得分:7)

Mirror library可以提供一些信息:

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

答案 1 :(得分:1)

import 'dart:io';
import 'package:reflection/reflection.dart';

void main() {
  var type = FileSystemEntity;
  var result = findAllSubclasses(typeInfo(type));
  var text = result.join("\r");
  print("==============================");
  print("Subclasses of '${type}'");
  print(text);
}

List<String> findAllSubclasses(TypeInfo type) {
  var typeOrig = type.originalDeclaration;
  var childs = MirrorSystemInfo.current.isolate.libraries.values
    .select((library) => library.getClasses(BindingFlags.PRIVATE | BindingFlags.PUBLIC).values)
    .selectMany((clazz) => clazz)
    .where((clazz) => clazz.isA(type) && clazz.originalDeclaration != typeOrig);
  return childs.toList();
}
==============================
Subclasses of FileSystemEntity
File
_Link
Directory
_File
_Directory
Link