Dart type check using "Type"

时间:2015-07-28 16:40:58

标签: dart

How to check type of Super class with Child class instance? I have below example and don't want to use dart-mirrors.

class SomeClass{

}

class SomeOtherClass extends SomeClass{

}
void main() {
  var s1 = new SomeOtherClass();
  someMethod(SomeClass, s1);
}

void someMethod(Type t, dynamic instance){
  print(instance.runtimeType == t);
  //print(instance.runtimeType is t); Does not work!
}

1 个答案:

答案 0 :(得分:1)

Update

Just today the package reflectable was released which allows to do this like with mirrors, but a transformer generates code instead to avoid using mirrors in production.

import 'package:reflectable/reflectable.dart';

// Annotate with this class to enable reflection.
class Reflector extends Reflectable {
  const Reflector()
  : super(typeCapability); // Request the capability to invoke methods.
}

const reflector = const Reflector();

@reflector
class SomeClass{

}

@reflector
class SomeOtherClass extends SomeClass{

}

void someMethod(Type t, dynamic instance){
  InstanceMirror instanceMirror = reflector.reflect(instance);
  print(instanceMirror.type.isSubclassOf(reflector.reflectType(t)));
}

void main() {
  var s1 = new SomeOtherClass();
  someMethod(SomeClass, s1);
}

Original

It might be directly supported when https://github.com/gbracha/metaclasses is implemented.

Currently this workaround can be used:

class IsInstanceOf<E> {
  bool check(t) => t is E;
}

void someMethod(Type t, dynamic instance){
  print( new IsInstanceOf<t>().check(instance));
  //print(instance.runtimeType is t); Does not work!
}

This runs fine and returns the correct result but the analyzer shows a warning because t can't be used as a type.

If you wrap SomeClass in a generic class it works without a warning

class SomeClass{

}

class SomeOtherClass extends SomeClass{

}

void main() {
  var s1 = new SomeOtherClass();
  someMethod(new IsInstanceOf<SomeClass>(), s1);
}

void someMethod(IsInstanceOf t, dynamic instance){
  print(t.check(instance));
  //print(instance.runtimeType is t); Does not work!
}

class IsInstanceOf<E> {
  bool check(instance) => instance is E;
}

Try it at DartPad