6

我有两个类ParserProxy,当我调用一个Parser不存在的方法时,它会将它委托给Proxy类。

我的代码:

class Parser {
    noSuchMethod(Invocation invocation) {
        // how to pass the `invocation` to `Proxy`???
    }
}

class Proxy {
    static String hello() { return "hello"; }
    static String world() { return "world"; }
}

当我写的时候:

var parser = new Parser();
print(parser.hello());

它将打印:

hello
4

4 回答 4

10

你必须使用dart:mirrors。这是怎么做的:

import 'dart:mirrors';

class Parser {
  noSuchMethod(Invocation invocation) {
    ClassMirror cm = reflectClass(Proxy);
    return cm.invoke(invocation.memberName
        , invocation.positionalArguments
        /*, invocation.namedArguments*/ // not implemented yet
        ).reflectee;
  }
}

class Proxy {
  static String hello() { return "hello"; }
  static String world() { return "world"; }
}

main(){
  var parser = new Parser();
  print(parser.hello());
  print(parser.world());
}
于 2013-07-03T08:31:29.997 回答
6

亚历山大的回答是正确的,但我想补充一点。

我假设委托Proxy是一个实现细节,我们不希望用户接触到它。parser在这种情况下,我们应该对调用不支持的方法的情况进行一些处理Proxy。现在,如果你这样做:

void main() {
  var parser = new Parser();
  print(parser.foo());
}

你得到这个错误:

Unhandled exception:
Compile-time error during mirrored execution: <Dart_Invoke: did not find static method 'Proxy.foo'.>

我会noSuchMethod以稍微不同的方式编写代码。在委托给 之前Proxy,我会检查它是否Proxy支持我将要调用的方法。如果Proxy支持它,我会调用ProxyAlexandre 在他的回答中描述的方法。如果Proxy不支持该方法,我会抛出一个NoSuchMethodError.

这是答案的修订版:

import 'dart:mirrors';

class Parser {
  noSuchMethod(Invocation invocation) {
    ClassMirror cm = reflectClass(Proxy);
    if (cm.methods.keys.contains(invocation.memberName)) {
      return cm.invoke(invocation.memberName
          , invocation.positionalArguments
          /*, invocation.namedArguments*/ // not implemented yet
          ).reflectee;
    }
    throw new NoSuchMethodError(this,
        _symbolToString(invocation.memberName),
        invocation.positionalArguments,
        _symbolMapToStringMap(invocation.namedArguments));
  }
}


String _symbolToString(Symbol symbol) => MirrorSystem.getName(symbol);

Map<String, dynamic> _symbolMapToStringMap(Map<Symbol, dynamic> map) {
  if (map == null) return null;
  var result = new Map<String, dynamic>();
  map.forEach((Symbol key, value) {
    result[_symbolToString(key)] = value;
  });
  return result;
}

class Proxy {
  static String hello() { return "hello"; }
  static String world() { return "world"; }
}

main(){
  var parser = new Parser();
  print(parser.hello());
  print(parser.world());
  print(parser.foo());
}

这是运行此代码的输出:

hello
world
Unhandled exception:
NoSuchMethodError : method not found: 'foo'
Receiver: Instance of 'Parser'
Arguments: []
于 2013-07-03T14:36:15.947 回答
3

我还要补充一点,如果您要委托给的事物集是固定的并且您可以合理地对其进行硬编码,那么您可以避免使用镜像。如果您使用静态方法,这特别容易,但我不清楚您为什么在这里这样做。我认为以下方法适用于实例方法和静态方法,但我在没有实际尝试的情况下输入了这段代码......

Function lookupMethod(Proxy p, Symbol name) {
  if (name == const Symbol("hello")) return p.hello;
  if (name == const Symbol("world")) return p.world;
  throw "Aaaaaagh";
}

noSuchMethod(invocation) => 
    Function.apply(lookupMethod(Proxy, invocation.memberName),
        invocation.positionalArguments);

如果转发的方法集发生变化,这很脆弱,但如果您使用镜像(目前几乎所有的 tree-shaking 禁用),可能有助于避免代码大小增加。

于 2013-07-03T17:03:21.650 回答
1

这个例子也可以帮助你理解:

void main() {
  var car = new CarProxy(new ProxyObjectImpl('Car'));
  testCar(car);

  var person = new PersonProxy(new ProxyObjectImpl('Person'));
  testPerson(person);
}

void testCar(Car car) {
  print(car.motor);
}

void testPerson(Person person) {
  print(person.age);
  print(person.name);
}

abstract class Car {
  String get motor;
}

abstract class Person {
  int get age;
  String get name;
}

class CarProxy implements Car {
  final ProxyObject _proxy;

  CarProxy(this._proxy);

  noSuchMethod(Invocation invocation) {
    return _proxy.handle(invocation);
  }
}

class PersonProxy implements Person {
  final ProxyObject _proxy;

  PersonProxy(this._proxy);

  noSuchMethod(Invocation invocation) {
    return _proxy.handle(invocation);
  }
}

abstract class ProxyObject {
  dynamic handle(Invocation invocation);
}

class ProxyObjectImpl implements ProxyObject {
  String type;
  int id;
  Map<Symbol, dynamic> properties;

  ProxyObjectImpl(this.type, [this.id]) {
    properties = ProxyManager.getProperties(type);
  }

  dynamic handle(Invocation invocation) {
    var memberName = invocation.memberName;

    if(invocation.isGetter) {
      if(properties.containsKey(memberName)) {
        return properties[memberName];
      }
    }

    throw "Runtime Error: $type has no $memberName member";
  }
}

class ProxyManager {
  static Map<Symbol, dynamic> getProperties(String name) {
    Map<Symbol, dynamic> properties = new Map<Symbol, dynamic>();
    switch(name) {
      case 'Car':
        properties[new Symbol('motor')] = 'xPowerDrive2013';
        break;
      case 'Person':
        properties[new Symbol('age')] = 42;
        properties[new Symbol('name')] = 'Bobby';
        break;
      default:
        throw new StateError('Entity not found: $name');
    }

    return properties;
  }
}
于 2013-07-04T06:38:23.040 回答