Dart-通过类名称调用类构造函数

时间:2019-05-10 10:51:54

标签: dart

我有以下代码:-

  switch (code) {
    case "BleDisconnectedException":
      throw BleDisconnectedException(msg, details);
    case "BleGattException":
      throw BleGattException(msg, details);
    case "BleGattCallbackTimeoutException":
      throw BleGattCallbackTimeoutException(msg, details);
    case "BleCharacteristicNotFoundException":
      throw BleCharacteristicNotFoundException(msg, details);
    case "BleGattCannotStartException":
      throw BleGattCannotStartException(msg, details);
    default:
      throw e;
  }

如何让dart自动进行切换,即以String的名称调用类构造函数?

1 个答案:

答案 0 :(得分:0)

据我所知,在当前的Dart中是不可能的,但是您可以执行以下操作:

var factories = Map<String, Object Function()>{'Foo', () => new Foo(), 'Bar', () => new Bar()};

Object instance = factories['Foo']();