Search code examples
dartdart-mirrors

Using reflection to inspect collections inside a class


I have code looking like this:

Zoo myZoo;

class Zoo {
  Park<Duck> ducks;
  Park<Lama> lamas;
}

class Park<E extends Animal> {
  ...
}

I need to know from a ClassMirror of Zoo how many Park there are and what kind of subtype of Animal they contains. Actually I'd need to retrieve the Duck and Lama TypeMirrors in this example.

So far I've been able to print that out by parsing strings, but I can't manage to actually retrieve the types.


Solution

  • Your question is not entirely clear to me but I guess this is what you are looking for

    void main() {
      ClassMirror cm = reflectClass(Zoo);
      cm.declarations.forEach((k, v) {
        if(v is VariableMirror) {
          if ((v as VariableMirror).type.typeArguments.where((t) => t.isSubtypeOf(reflectType(Animal))).length > 0) {
            print('$k, $v');
          }
        }
      });
    }