I have three classes in dart:
class A {}
class B extends A{}
class C extends A{}
There is a way to get all subclasses from A?
Edit:
Thanks Alexandre Ardhuin your solution worked perfectly!
I'm learning the dart i edited your code and put the recursive solution, take a look:
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);
}
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
来源:https://stackoverflow.com/questions/16150437/find-all-subclasses-in-dart