Daniel Robinson
Daniel Robinson

Reputation: 14848

How to get declared type with mirrors?

import 'dart:mirrors';


void main() {
  var mirror = reflectClass(MyClass);
  mirror.declarations.forEach((k, v){
    print(k);
    if(v is VariableMirror){
      print(v.type);
    }
  });
}


class MyClass{
  var aDynamic;
  int anInt;
}

//prints:
Symbol("aDynamic")
TypeMirror on 'dynamic'
Symbol("anInt")
ClassMirror on 'int'
Symbol("MyClass")

is there a way I can get the Type the TypeMirror is refelcting so Id like to return a type of dynamic and of type int for the 2 properties in the example above?

Upvotes: 4

Views: 516

Answers (1)

Justin Fagnani
Justin Fagnani

Reputation: 11171

VariableMirror.type is the right way to go. If it returns a ClassMirror, then you can use ClassMirror.reflectedType to get the Type object for the declaration.

VariableMirror.type will be the declared type of the variable, not the type of any value the variable holds, so while it will be a TypeMirror it might not be a ClassMirror. It could also be a TypeVariableMirror or TypedefMirror. You can see in your output that the mirror for the dynamic case is a TypeMirror on dynamic. So you have to figure out how to deal with those. For instance, there is no Type object that represents dynamic, so you have to handle that separately. I would probably just convert it to Object. For TypedefMirrors, you could return Function. I'm not actually sure what other TypeMirrors that aren't a subtype there might be.

Here's some example code:

final _dynamicType = reflectType(dynamic);

Type getDeclaredType(VariableMirror m) {
  var t = m.type;
  if (t is ClassMirror) return t.reflectedType;
  if (t is TypedefMirror) return Function;
  if (t == _dynamicType) return Object;
  throw new ArgumentError("I don't know how to handle ${t}");
}

Upvotes: 4

Related Questions