Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

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

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...