I'm trying to build an entity manager in Dart which uses reflection. The idea is that the method getById(String id, String returnClass) calls a method _get[returnClass]ById(String id).

To accomplish this I'm using dart:mirrors and try to determine if my entity manager object has such a method and call it then. Unfortunately the LibraryMirror doesn't contain any functions.

class EntityMgr {

  Object getById(String id, String returnClass) {
    InstanceMirror result = null;
    String methodName = '_get'+returnClass+'ById';

    // Check if a method '_get[returnClass]Byid exists and call it with given ID
    if(_existsFunction(methodName)) {
      Symbol symbol = new Symbol(methodName);
      List methodParameters = new List();
           methodParameters.add(id);

      result = currentMirrorSystem().isolate.rootLibrary.invoke(symbol, methodParameters);
    }

    return result;
  }

  Product _getProductById(String id) {
    return new Product();
  }

  bool _existsFunction(String functionName) {
    return currentMirrorSystem().isolate.rootLibrary.functions.containsKey(functionName);
  } 
}
有帮助吗?

解决方案

The mirrors library has changed significantly since this response and no longer reflects the api mentioned in this answer

Isolate's are for concurrent programming and you probably don't have any isolates running. Where you want to look is currentMirrorSystem().libraries, or you can use currentMirrorSystem().findLibrary(new Symbol('library_name')).

You need to know the library because a function or class with the same Symbol could me in different libraries but have completely different signatures.

how to invoke class form dart library string or file shows how to get the class mirror from the library and class name.

The ClassMirror contains the methods, the getters and the setters. The methods mirror does not contain the getters or setters.

final Map<Symbol, MethodMirror> methods
final Map<Symbol, MethodMirror> getters
final Map<Symbol, MethodMirror> setters

That being said, you might want to check out the dart serialization at http://api.dartlang.org/docs/bleeding_edge/serialization.html since it might already do exactly what you're trying to do.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top