【发布时间】:2021-12-10 08:42:07
【问题描述】:
有没有办法在 Dart 中反映特定的库属性(如库名)? 如何获取库对象引用?
【问题讨论】:
标签: dart reflection dart-mirrors
有没有办法在 Dart 中反映特定的库属性(如库名)? 如何获取库对象引用?
【问题讨论】:
标签: dart reflection dart-mirrors
首先,并不是所有的 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);
}
你想做什么,需要反思?
【讨论】: