[英]Dart/Flutter - Call constructor of unknown concrete class (get class from Type)
I want to call the constructor of a concrete class, but I only have a Type
which implements an interface.我想调用一个具体的 class 的构造函数,但我只有一个实现接口的Type
。 Is it possible to get the concrete class from that Type
and call its constructor without actually having to know it?是否可以从该Type
中获取具体的 class 并调用其构造函数而无需实际知道它?
My current workaround is a switch with a cast, but that does not seem reasonable, because I have to maintain the switch whenever another class implements that interface.我当前的解决方法是使用强制转换的开关,但这似乎不合理,因为每当另一个 class 实现该接口时,我都必须维护该开关。
abstract class IFace {
String foo();
}
class Bar implements IFace {
String foo() => 'I am Bar';
}
T? getObject<T extends IFace>() {
// what I'd like to do, but does not work:
// return T();
// what I have to do instead:
switch (T) {
case Bar:
return Bar() as T;
default:
return null;
}
}
void main() {
Bar? bar = getObject<Bar>();
print(bar?.foo()); // I am Bar
}
This is not easy thing to do just because, what if T does not have public constructor, or it has named constructor instead?这不是一件容易的事,因为如果 T 没有公共构造函数,或者它有命名构造函数怎么办? ;) ;)
I think it could be possible only with use of dart:mirrors package, which is not available on Flutter (due to AOT compilation).我认为只有使用 dart:mirrors package 才有可能,这在 Flutter 上不可用(由于 AOT 编译)。
As alternative, you can try using reflectable package, but it is not easy to do either.作为替代方案,您可以尝试使用可反射的 package,但这也不是一件容易的事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.