此代码不适用于Dart VM (1.22.0dev.9.0),但在DartPad (未知版本)上工作:
import 'dart:mirrors';
class Thing {
Thing();
}
void g(ClassMirror c) {
var constructors = c.declarations.values
.where((d) => d is MethodMirror && d.isConstructor) as Iterable<MethodMirror>;
print(constructors);
}
void main() {
g(reflectClass(Thing));
}在以下方面的成果:
Unhandled exception:
type 'WhereIterable<DeclarationMirror>' is not a subtype of type 'Iterable<MethodMirror>' in type cast where
WhereIterable is from dart:_internal
DeclarationMirror is from dart:mirrors
Iterable is from dart:core
MethodMirror is from dart:mirrors
#0 Object._as (dart:core-patch/object_patch.dart:76)
#1 g (file:///google/src/cloud/srawlins/strong/google3/b.dart:9:55)
#2 main (file:///google/src/cloud/srawlins/strong/google3/b.dart:14:3)
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)(但在DartPad中,结果是(MethodMirror on 'Thing').)
请注意,如果我手工创建了一些相互实现的类,并执行相同的操作,它就会工作:
abstract class DM {
bool get t;
}
abstract class MM implements DM {
MM();
bool get t;
}
class _MM implements MM {
bool get t => true;
}
void f(Map<dynamic, DM> dms) {
var mms = dms.values.where((dm) => dm is MM && dm.t) as Iterable<MM>;
print(mms);
}
void main() {
f({1: new _MM()});
}很好地打印:(Instance of '_MM')
发布于 2017-01-21 16:33:54
仅仅因为.where()返回的可迭代性只能包含MethodMirror实例,就不允许转换。类型是从c.declarations.values (即DeclarationMirror )传播的。虽然您可以将DeclarationMirror转换为MethodMirror,但是从Iterable<DeclarationMirror>到Iterable<MethodMirror>的转换是无效的,因为没有is --这些与可迭代性之间的关系。
当由dart2js构建到JS时,似乎会删除一些泛型类型,这就是为什么在DartPad中这样做的原因。
您可以创建一个新的List<MethodMirror>,如
import 'dart:mirrors';
class Thing {
Thing();
}
void g(ClassMirror c) {
var constructors = new List<MethodMirror>.from(
c.declarations.values.where((d) => d is MethodMirror && d.isConstructor));
print(constructors);
}
void main() {
g(reflectClass(Thing));
}有一个悬而未决的问题可以使https://github.com/dart-lang/sdk/issues/27489变得更容易
https://stackoverflow.com/questions/41773514
复制相似问题