【问题标题】:How to reflect Dart library name?如何反映 Dart 库名称?
【发布时间】:2021-12-10 08:42:07
【问题描述】:

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

【问题讨论】:

    标签: dart reflection dart-mirrors


    【解决方案1】:

    首先,并不是所有的 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);
    }
    

    你想做什么,需要反思?

    【讨论】:

    • @Irn,感谢您提供详细示例!这正是我想要的。
    • 最后一次打印应该是:print(alsoCurrentLibrary.simpleName);顺便说一句,就我而言,它打印: Symbol("dart.core")
    • 不错,已修复。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多