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

StackOverflow https://stackoverflow.com/questions/21851931

  •  13-10-2022
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top