How can I get the concrete type of a generic type variable using mirrors in Dart?

自闭症网瘾萝莉.ら 提交于 2020-01-04 02:51:09

问题


Assuming I have a List of Strings like this.

var myList = new List<String>();

How can I figure out that myList is a List of Strings 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!