如何反映 Dart 库名称?

How to reflect Dart library name?

有没有办法在 Dart 中反映特定的库属性(如库名称)? 您如何获取库对象引用?

首先,并不是所有的 Dart 库都有名字。事实上,大多数人没有。他们曾经使用过,但这个名称不再用于任何用途,因此大多数库作者都懒得添加名称。

要对包括库在内的任何事物进行反思,您需要使用 dart:mirrors 库,该库在大多数平台(包括 Web 和 Flutter)上都不存在。 如果您不是 运行 独立 VM,您可能没有 dart:mirrors.

使用dart:mirrors,您可以通过多种方式获取程序的库。

library my.library.name;

import "dart:mirrors";

final List<LibraryMirror> allLibraries = 
    [...currentMirrorSystem().libraries.values];

void main() {
  // Recognize the library's mirror in *some* way.
  var someLibrary = allLibraries.firstWhere((LibraryMirror library) => 
     library.simpleName.toString().contains("name"));
  
  // Find the library mirror by its name. 
  // Not great if you don't know the name and want to find it.
  var currentLibrary = currentMirrorSystem().findLibrary(#my.library.name);
  print(currentLibrary.simpleName);

  // Find a declaration in the current library, and start from there.
  var mainFunction = reflect(main) as ClosureMirror;
  var alsoCurrentLibrary = mainFunction.function.owner as LibraryMirror;
  print(alsoCurrentLibrary.simpleName);
}

你想做什么,需要反思吗?