gpt4 book ai didi

dart - 如何调用类形式 dart 库字符串或文件

转载 作者:行者123 更新时间:2023-12-04 20:09:59 24 4
gpt4 key购买 nike

谁来调用类表单 dart 库字符串或文件?

例如

for-load.dart 文件

class TestLoad {
void requestHandler(){
}
}

然后 main.dart 文件

main(){
//this get load lib
var lib = currentMirrorSystem().libraries[Uri.parse('dart:core')];
//who to invoke class form TestLoad or for-load.dart?
//like java Class.forName('TestLoad') , nodejs require('for-load')
}

谢谢!

最佳答案

这些符号是要动态调用的库、类和类的构造函数的名称

foo.dart

library foo_library;

class Foo {
String bar;
}

invoke_class.dart

library new_instance_test;

import "dart:mirrors";
import "foo.dart";

int main() {
// These symbols are the names of the Library, the Class and the constructor for the Class that you want to dynamically load
final Symbol librarySymbol = const Symbol("foo_library");
final Symbol classSymbol = const Symbol("Foo");
final Symbol constructorSymbol = const Symbol("");

MirrorSystem mirrorSystem = currentMirrorSystem();

// Get LibraryMirror for Library foo_library.
// It returns an iterator, get the first LibraryMirror
LibraryMirror libraryMirror = mirrorSystem.findLibrary(librarySymbol).first;

// Get ClassMirror for Class Foo
ClassMirror classMirror = libraryMirror.declarations[classSymbol];

// Get the InstanceMirror using the default constructor
InstanceMirror testClassInstanceMirror = classMirror.newInstance(constructorSymbol, []);

//Get the reflectee object from the InstanceMirror
Foo foo = testClassInstanceMirror.reflectee;

//Set bar and print it
foo.bar = "foobar";
print(foo.bar);
}

关于dart - 如何调用类形式 dart 库字符串或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19166146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com