Dynamic class method invocation in Dart

会有一股神秘感。 提交于 2019-11-27 06:48:50

问题


Like the question at Dynamic class method invocation in PHP I want to do this in Dart.

var = "name";
page.${var} = value;
page.save();

Is that possible?


回答1:


There are several things you can achieve with Mirrors.

Here's an example how to set values of classes and how to call methods dynamically:

import 'dart:mirrors';

class Page {
  var name;

  method() {
    print('called!');
  }
}

void main() {
  var page = new Page();

  var im = reflect(page);

  // Set values.
  im.setField("name", "some value").then((temp) => print(page.name));

  // Call methods.
  im.invoke("method", []);
}

In case you wonder, im is an InstanceMirror, which basically reflects the page instance.

There is also another question: Is there a way to dynamically call a method or set an instance variable in a class in Dart?




回答2:


You can use Dart Mirror API to do such thing. Mirror API is not fully implemented now but here's how it could work :

import 'dart:mirrors';

class Page {
  String name;
}

main() {
  final page = new Page();
  var value = "value";

  InstanceMirror im = reflect(page);
  im.setField("name", value).then((_){
    print(page.name); // display "value"
  });
}



回答3:


You can use Serializable

For example:

import 'package:serializable/serializable.dart';

@serializable
class Page extends _$PageSerializable {
  String name;
}

main() {
  final page = new Page();
  var attribute = "name";
  var value = "value";

  page["name"] = value;
  page[attribute] = value;

  print("page.name: ${page['name']}");
}


来源:https://stackoverflow.com/questions/13293345/dynamic-class-method-invocation-in-dart

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