Dynamic type conversion with mirrors



Is it possible to cast dynamically to a type?

For example, could this be possible, using mirrors:

var reflectee = im.getField(simpleName).reflectee;

var converted = testVal as reflectee.runtimeType;

I want to make a Mixin class which defines a validate method:

abstract class Validatable {
  bool validate(Map document) {

It will iterate over the variables defined for the class where it is mixed in, and checks if the variable in the document are of the same type.

Now, it is working with getting the runtimeType of the respective variables, but it is very restrictive as it does not cast. For example:

var a = 1.1;
var b = 1;
print(a.runtimeType == b.runtimeType); // false

It would be better to better to check with as, but I cant see how to get this to work. Becase:

a = b;
print(a.runtimeType); // int

and not double, as one might expect.

Is it possible?


You could use

import 'dart:mirrors';

class A {


class B extends A {


class C extends A {


void main(args) {
  var a = 1.1;
  var b = 1;
  var x = reflect(b);

  var myb = new B();


Answered By – Günter Zöchbauer

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *