在Dart中,使用Mirrors,如何从类的实例中调用类的静态方法?

时间:2013-12-23 12:14:18

标签: class reflection static dart dart-mirrors

如果我有一个实例,并且我知道实例的类包含一个名为statFn()的静态方法,那么如何从实例中调用statFn()

例如,

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?

2 个答案:

答案 0 :(得分:4)

这应该让你开始。 findStaticAndInvoke()查看提供的对象的类及其静态方法或getter的子类,并在找到时调用它。

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, []);
    }
  }
}

答案 1 :(得分:1)

在服务器端(使用纯Dart语言但不使用Javascript),您可以尝试使用reflection库。它被写为dart:mirrors库的叠加层。

它具有相同的功能和一些其他有用的功能。

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