我有一个MethodMirror
,想要检查其镜像方法是否正在实现typedef
。这有可能吗?
最佳答案
我在'dart:mirrors'中找不到预定义的方法来检查某个方法是否是typedef的实例。
这段代码似乎可以正常工作(未经全面测试)
import 'dart:mirrors';
typedef MyFunc(int a, String b);
main() {
MethodMirror mm = reflectClass(TestClass).declarations[#testFunc1];
FunctionTypeMirror tdm =(reflectType(MyFunc) as TypedefMirror).referent;
print(isOfTypeDef(mm, tdm));
mm = reflectClass(TestClass).declarations[#testFunc2];
print(isOfTypeDef(mm, tdm));
mm = reflectClass(TestClass).declarations[#testFunc3];
print(isOfTypeDef(mm, tdm));
}
class TestClass {
void testFunc1(int c, String d) {
print('$c, $d');
}
void testFunc2(var c, var d) {
print('$c, $d');
}
void testFunc3(int e, int f) {
print('$e, $f');
}
}
bool isOfTypeDef(MethodMirror mm, FunctionTypeMirror tdm) {
if((mm.returnType.isAssignableTo(tdm.returnType)) && (mm.parameters.length == tdm.parameters.length)) {
for(int i = 0; i < mm.parameters.length; i++) {
if(!mm.parameters[i].type.isAssignableTo(tdm.parameters[i].type)) {
return false;
}
};
}
return true;
}
我认为值得http://dartbug.com提出功能要求
关于reflection - 如何检查方法镜像是否实现typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23497032/