Is there a way to dynamically call a method or set an instance variable in a class in Dart?

我只是一个虾纸丫 提交于 2019-12-23 15:42:44

问题


I would want to be able to do something like this with a Dart class constructor:

class Model {

  // ... setting instance variables

  Model(Map fields) {
    fields.forEach((k,v) => this[k] = v);
  }

}

Obviously, this doesn't work, because this doesn't have a []= method.

Is there a way to make it work or is it simply not "the dart way" of doing things? If it's not, could you show me what would be the right way to tackle this?


回答1:


Currently no. You will have to wait for reflection to arrive in Dart before something like this (hopefully) becomes possible. Until then your best bet is probably to do it in a constructor. Alternatively you could try to use something like JsonObject which allows you to directly initialize it from a Map (for an explanation on how this works, check this blog post).




回答2:


You can use Mirrors:

InstanceMirror im = reflect(theClassInstance);

im.invoke('methodName', ['param 1', 2, 'foo']).then((InstanceMirror value) {
  print(value.reflectee); // This is the return value of the method invocation.
});

So, in your case you could do this (since you have setters):

import 'dart:mirrors';

class Model {
  Model(Map fields) {
    InstanceMirror im = reflect(this);
    fields.forEach((k, v) => im.setField(k, v)); // or just fields.forEach(im.setField);
  }
}

The documentation for InstanceMirror might come in handy.



来源:https://stackoverflow.com/questions/10525929/is-there-a-way-to-dynamically-call-a-method-or-set-an-instance-variable-in-a-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!