Search code examples
genericsdartdart-mirrors

Find generic type of Iterable (Set<E>, List<E>, ...) via introspection


I tried without any success to find the generic type of an Iterable class (such as Set<myGenericType> or List<myOtherGenericType>).

For instance :

if instanceMirror.getField(myField).reflectee is a Set<Toto> then I have no solution to retrieve the type Toto via introspection.

Thank you for your help !


Solution

  • import 'dart:mirrors';
    
    class A<T> {
      T item;
      List<T> items;
    }
    
    main() {
      var m = reflectType(new A<int>().runtimeType);
    
      var itemType = m.declarations[#item].type as TypeMirror;
      print('type of #item: ${itemType.qualifiedName}');  // type of #item: ClassMirror on 'int'.
    
      var itemsType = m.declarations[#items].type as ClassMirror;
      print('type of #items: ${itemsType.qualifiedName}');  // type of #items: ClassMirror on 'List'.
    
      print('type arguments of #items: ${itemsType.typeArguments.map((t) => t.qualifiedName)}');  // type arguments of #items: [TypeVariableMirror on 'T'].
    }