Find all subclasses in dart

你离开我真会死。 提交于 2019-11-29 07:05:26

Mirror library can provide some infos :

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

The output will be :

C has A as super class
B has A as super class
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!