in Dart, using Mirrors, how would you call a class's static method from an instance of the class?

情到浓时终转凉″ 提交于 2019-12-18 09:07:05

问题


if I have an instance, and I know the instance's class contains a static method named statFn(), how do I call statFn() from the instance?

for example,

abstract class Junk {
  ...
}
class Hamburger extends Junk {
  static bool get lettuce => true;
  ...
}
class HotDog extends Junk {
  static bool get lettuce => false;
  ...
}

Junk food; // either Hamburger or Hotdog

// how do you get lettuce of food's type?

回答1:


This should get you started. findStaticAndInvoke() looks at the class of the provided object and it's subclasses for the static method or getter and invokes it when found.

library x;

import 'dart:mirrors';

abstract class Junk {
  static void doSomething() {
    print("Junk.doSomething()");
  }
}

class Hamburger extends Junk {
  static bool get lettuce => true;
}

class HotDog extends Junk {
  static bool get lettuce => false;
}

Junk food; // either Hamburger or Hotdog

void main(List<String> args) {
  Junk food = new HotDog();
  findStaticAndInvoke(food, "doSomething");
  findStaticAndInvoke(food, "lettuce");

  food = new Hamburger();
  findStaticAndInvoke(food, "doSomething");
  findStaticAndInvoke(food, "lettuce");
}

void findStaticAndInvoke(o, String name) {
  ClassMirror r = reflect(o).type;
  MethodMirror sFn;
  var s = new Symbol(name);

  while (sFn == null && r != null) {
    sFn = r.staticMembers[s];
    if(sFn != null) {
      break;
    }
    r = r.superclass;
  }

  if(sFn != null) {
    if(sFn.isGetter) {
      print(r.getField(s).reflectee);
    }
    else {
      r.invoke(s, []);
    }
  }
}



回答2:


On the server side (in pure Dart language but not in Javascript) you can try to use the reflection library. It written as an overlay over the dart:mirrors library.

It has the same functionality and some additional useful features.

import 'package:reflection/reflection.dart';

abstract class Junk {
  bool _fresh = true;
  bool get fresh => _fresh;
  void set fresh(fresh) { _fresh = fresh; }
}
class Hamburger extends Junk {
  static bool get lettuce => true;
}
class HotDog extends Junk {
  static bool get lettuce => false;
}

Junk food;

void main() {
  food = new Hamburger();
  var type = objectInfo(food).type;
  var lettuce = type.getProperty(#lettuce, BindingFlags.PUBLIC | BindingFlags.STATIC);
  print(lettuce.getValue());

  // Default: BindingFlags.PUBLIC | BindingFlags.INSTANCE
  var fresh = type.getProperty(#fresh);
  print(fresh.getValue(food));

  // Stale
  fresh.setValue(food, false);
  print(fresh.getValue(food));
}
true
true
false


来源:https://stackoverflow.com/questions/20743346/in-dart-using-mirrors-how-would-you-call-a-classs-static-method-from-an-insta

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