You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

dart:mirrors的reflectType()未返回TypedefMirror问题咨询

Dart中dart:mirrors获取typedef镜像的疑问

我运行了以下Dart代码:

import 'dart:mirrors';

typedef Func();

void main() {
  final m = reflectType(Func);
  print(m);
}

我期望m是TypedefMirror的引用,但实际输出为:

FunctionTypeMirror on '() -> dynamic'

这与我在GitHub上找到的部分测试用例不符。我想知道自己忽略了什么?是否可以通过dart:mirrors获取原始typedef的名称?

我的Dart SDK版本:

> dart --version
Dart SDK version: 2.19.2 (stable) (Tue Feb 7 18:37:17 2023 +0000) on "windows_x64"

问题原因

Dart的reflectType(Func)会直接返回该typedef对应的函数类型镜像(FunctionTypeMirror),而非TypedefMirror。这是因为typedef在Dart中本质是函数类型的别名,当你直接将Func传入reflectType时,它解析的是别名指向的底层类型,而非别名本身的镜像。

获取TypedefMirror及原始名称的方法

要获取typedef自身的TypedefMirror并拿到其名称,需要通过包含该typedef的库镜像来查找:

import 'dart:mirrors';

typedef Func();

void main() {
  // 获取当前代码所在库的镜像
  final libMirror = currentMirrorSystem().findLibrary(#main);
  
  // 遍历库内所有声明,筛选目标TypedefMirror
  for (final declaration in libMirror.declarations.values) {
    if (declaration is TypedefMirror && declaration.simpleName == #Func) {
      print(declaration); // 输出: TypedefMirror on 'Func'
      print(MirrorSystem.getName(declaration.simpleName)); // 输出: Func
    }
  }
}

关键说明

  • currentMirrorSystem().findLibrary(#main) 获取当前执行代码所在的库镜像,若你的库有自定义名称,需将#main替换为对应库的符号。
  • 通过遍历库的declarations集合,筛选出类型为TypedefMirror且名称匹配的项,就能拿到typedef自身的镜像,进而通过MirrorSystem.getName()获取其字符串形式的名称。

早期测试用例的行为可能基于旧版Dart SDK,当时reflectType对typedef的处理逻辑与当前稳定版(2.19.2)不同,当前版本会将typedef视为类型别名,直接返回其指向的函数类型镜像。


内容的提问来源于stack exchange,提问作者Marton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:23:23