8

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);
}
Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
lucianoshl
  • 83
  • 5
  • I'm curious what you're actually trying to accomplish. This is one of those cases where the answer to your question is a simple "No," and we can't really help any more than that without knowing what the actual goal is. – Darshan Rivka Whittle Apr 22 '13 at 20:34
  • I would recommend using reflectable lib since it is better to use with dart2js and it is also provided by the dart team – Jonathan Nov 14 '16 at 09:47

1 Answers1

8

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
Alexandre Ardhuin
  • 52,177
  • 8
  • 124
  • 113
  • I think you should be able to avoid going through the names, and just compare the superclass to a class mirror on the one you want. For proper generality you also need to iterate over all the libraries. – Alan Knight Apr 23 '13 at 14:31
  • suppose `class E extends C {}` - E has A as superclass, but this wouldn't be included in the output. Maybe some recursive solution? – MarioP Apr 24 '13 at 12:19
  • 1
    Sure, you have to make some recursions to get all subclasses. The code snippet here is only to show a basic example to find direct children. It has to be refined to get all subclasses... My intent was to show how to get started. – Alexandre Ardhuin Apr 24 '13 at 12:32