在Dart中,使用Mirrors,你将如何从类的实例调用类的静态方法? [英] in Dart, using Mirrors, how would you call a class's static method from an instance of the class?

查看:601
本文介绍了在Dart中,使用Mirrors,你将如何从类的实例调用类的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 $ HB $ b$ {
...
}
类别Hamburger extends Junk {
static bool get lettuce =>真正;
...
}
类HotDog extends Junk {
static bool get lettuce =>假;
...
}

垃圾食品; //汉堡包或热狗

//你如何获得食物类型的莴苣?


解决方案


findStaticAndInvoke()查看提供的对象的类,它是静态方法或getter的子类,并在找到时调用它。

  library x; 

import'dart:mirrors';

抽象类Junk {
static void doSomething(){
print(Junk.doSomething());
}
}

类Hamburger extends Junk {
static bool get lettuce =>真正;
}

类HotDog extends Junk {
static bool get lettuce =>假;
}

垃圾食品; //汉堡包或热狗

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


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?

解决方案

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

这篇关于在Dart中,使用Mirrors,你将如何从类的实例调用类的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆