質問

Problem:

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;

Context: 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);
  print(x.type.isSubtypeOf(reflectType(num)));
  print(x.type.isAssignableTo(reflectType(num)));
  print(x.type.isAssignableTo(reflectType(double)));

  var myb = new B();

  print(reflect(myb).type.isSubtypeOf(reflectType(A)));
  print(reflect(myb).type.isAssignableTo(reflectType(A)));
  print(reflect(myb).type.isAssignableTo(reflectType(C)));    
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top