gpt4 book ai didi

Dart 镜像 API : Getting the result of a reflection call

转载 作者:行者123 更新时间:2023-12-03 02:54:22 26 4
gpt4 key购买 nike

让镜像返回 future 极大地限制了你可以用它们做的事情。

例如,

class ObjectA {
methodA(){}
methodB(){}
}

class DynamicWrapper extends MagicalDynamicWrapper {
ObjectA real;
Map<String, Function> methods;
DynamicWrapper(this.real, this.methods);
}

var w = new DynamicWrapper(new ObjectA(), {"methodB" : (){ 'do something' }});
w.methodA() // calls ObjectA.methodA
w.methodB() // calls 'do something'

我通常这样做的方法是在 MagicalDynamicWrapper 中定义 noSuchMethod:
  • 这将检查方法映射中是否存在具有此类名称的方法,然后调用它。
  • 如果没有,它将通过反射调用“真实”对象。

  • 不幸的是,调用真实对象总是会返回一个 future 。所以它不起作用。

    在某些时候,可以获得 Future 的值(使用 value getter),但该 getter 不再可用。

    我的问题:

    有没有办法同步获取反射调用的结果?

    在分布式环境中, future 绝对是必经之路。但是在非分布式设置中,所有元信息都可用,应该可以获取反射调用的值。我会对测试框架和构建工具的作者产生巨大影响。

    最佳答案

    Having mirrors returning futures certainly makes sense



    不,它没有(好吧,至少对我来说不是 :-) )。它可能会被改变,见 http://dartbug.com/4633#c17

    The way I'd normally do it is by defining noSuchMethod in MagicalDynamicWrapper that will check if there is a method with such a name in the methods map, then call it, and if there is none, it will call the "real" object via reflection.



    检查 InvocationMirror文档。您可以使用 invokeOn 转发方法调用方法:

    class Proxy {
    var target;
    Map<String, Function> overrides;

    Proxy(this.target, this.overrides);

    noSuchMethod(invocation) {
    if (overrides.containsKey(invocation.memberName)) {
    return overrides[invocation.memberName]();
    } else {
    return invocation.invokeOn(target);
    }
    }
    }

    Is there a way to get the result of a reflection call synchronously?



    不,不是。不是现在。您可以加星 http://dartbug.com/4633如果你愿意。

    关于Dart 镜像 API : Getting the result of a reflection call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042187/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com