Daniel Robinson
Daniel Robinson

Reputation: 14878

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

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?

Upvotes: 2

Views: 88

Answers (1)

MarioP
MarioP

Reputation: 3832

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

Upvotes: 1

Related Questions