According to this test, I can not invoke the method "method" with an argument "list" because argument type is not compatible with the type of the method parameter.
Where I am wrong in my test?
import "dart:mirrors";
void main() {
var list = new List<String>();
var listMirror = reflectClass(list.runtimeType);
// Is "List<String>" subtype of "List<String>"?
print(listMirror.isSubtypeOf(listMirror));
// Method with parameter "List<String>"
var method = (List<String> list) {};
var closure = reflect(method) as ClosureMirror;
var function = closure.function;
var parameter = function.parameters.first;
// Is "List<String>" subtype of "List<String>"?
print(parameter.type.isSubtypeOf(listMirror));
print(listMirror.isSubtypeOf(parameter.type));
// Invoke method with arg: "List<String>" on param "List<String>"
method(list);
}
Output:
true
false
false
P.S.
Maybe I not understand something but it still not works.
import "dart:mirrors";
void main() {
var stringMirror = reflectClass(String);
// Query "List<int> get codeUnits"
MethodMirror method = stringMirror.declarations.values
.where((e) => e.simpleName == #codeUnits).first;
// List<int>
var returnType = method.returnType;
print(returnType);
// List
var baseType = reflectClass(List);
print(baseType);
// List<int> is List
print(returnType.isSubtypeOf(baseType));
}
Output:
ClassMirror on 'List'
ClassMirror on 'List'
false
This line is the culprit:
var listMirror = reflectClass(list.runtimeType);
it returns
ClassMirror on '_GrowableList'
if you use
var listMirror = reflectType(List);
it should work.
What you can when you need to get the type from a value at runtime
var listMirror = reflect(list).type.superinterfaces;
...
listMirror.forEach((e) => print(parameter.type.isSubtypeOf(e)));
depending on the situation you may need to make additional checks with
reflect(list).type.mixin;
If one of these checks is true it is a subtype.