问题
Assuming I have a List
of String
s like this.
var myList = new List<String>();
How can I figure out that myList
is a List
of String
s using mirrors?
I tried it using the typeVariables
of ClassMirror
but the mirror seems to just describe the gerneric List
class.
InstanceMirror im = reflect(myList); // InstanceMirror on instance of 'List'
ClassMirror cm = im.type; // ClassMirror on 'List'
print(cm.typeVariables['E']) // TypeVariableMirror on 'E'
I also found this in the documentation but I have yet to find a ClassMirror
instance where accessing originalDeclaration
doesn't throw a NoSuchMethodError
.
final ClassMirror originalDeclaration
A mirror on the original declaration of this type.
For most classes, they are their own original declaration. For generic classes, however, there is a distinction between the original class declaration, which has unbound type variables, and the instantiations of generic classes, which have bound type variables.
回答1:
2 possible methods.
The first method is to check the variable's type using is
operator, as it's more performant than reflection:
var myList = new List<String>();
print(myList is List<int>); // false
print(myList is List<String>); // true
The second method is to use ClassMirror.typeArguments:
import 'dart:mirrors';
var myList = new List<String>();
Map typeArguments = reflect(myList).type.typeArguments;
print(typeArguments); // {Symbol("T"): ClassMirror on 'String'}
ClassMirror firstTypeArg = typeArguments[typeArguments.keys.first];
print(firstTypeArg.reflectedType); // String
来源:https://stackoverflow.com/questions/14384865/how-can-i-get-the-concrete-type-of-a-generic-type-variable-using-mirrors-in-dart