dart, given an instance of a class is it possible to get a list of all the types it inherits from in ascending order?

Issue

if I have:

List<Type> getInheritanceStructure(){
    // TODO
}

class A{
}
class B extends A{
}
class C extends B{
}

var c = new C();

List<Type> types = getInheritanceStructure(c);

types.forEach((type) => print(type));

//should print out:
C
B
A
Object

is it possible to get a list of Types like this?

Solution

You need a class mirror, from there you can walk through all the superclasses.

List<Type> getInheritanceStructure(Object o){
    ClassMirror baseClass = reflectClass(o.runtimeType);
    return walkSuperclasses(baseClass);
}

List<Type> walkSuperclasses(ClassMirror cm) {
    List<Type> l = [];
    l.add(cm.reflectedType);
    if(cm.superclass != null) {
        l.addAll(walkSuperclasses(cm.superclass));
    }
    return l;
}

Answered By – MarioP

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *