Instantiate a class from a string

与世无争的帅哥 提交于 2019-11-27 05:07:22

You need to know the library name and class name to make things work properly. Assume you know both, the below example will instantiate the TestClass and call doStuff on it.

library test;

import "dart:mirrors";

class TestClass {
  doStuff() => print("doStuff was called!");
}

main() {
  MirrorSystem mirrors = currentMirrorSystem();
  LibraryMirror lm = mirrors.libraries['test'];
  ClassMirror cm = lm.classes['TestClass'];
  Future tcFuture = cm.newInstance('', []);
  tcFuture.then((InstanceMirror im) {
    var tc = im.reflectee;
    tc.doStuff();
  });
}

A few notes about this solution:

  1. The library test we are trying to load the class from is already imported in the VM, which makes this case a bit easier.
  2. the call the newInstance allows for passing parameters to the constructor. Positional arguments are implemented, but named parameters are not yet implemented (as of the M2 release).
  3. newInstance returns a Future to allow it to work across isolates.

The syntax has changed. I got it working this way

library test;

import "dart:mirrors";

class TestClass {
  doStuff() => print("doStuff was called!");
}

main() {
  MirrorSystem mirrors = currentMirrorSystem();
  LibraryMirror lm = mirrors.libraries.values.firstWhere(
      (LibraryMirror lm) => lm.qualifiedName == new Symbol('test'));

  ClassMirror cm = lm.declarations[new Symbol('TestClass')];

  InstanceMirror im = cm.newInstance(new Symbol(''), []);
  var tc = im.reflectee;
  tc.doStuff();
}

If there are more libraries named 'test' this will fail though.

This was an issue that has plagued me until I figured that I could implement a crude from method to handle the conversion of encoded Json Objects/strings or Dart Maps to the desired class.

Below is a simple example that also handles nulls and accepts JSON (as the string parameter)

import 'dart:convert';

class PaymentDetail
{
  String AccountNumber;
  double Amount;
  int ChargeTypeID;
  String CustomerNames;

  PaymentDetail({
    this.AccountNumber,
    this.Amount,
    this.ChargeTypeID,
    this.CustomerNames
  });

  PaymentDetail from ({ string : String, object : Map  }) {
     var map   = (object==null) ? (string==null) ? Map() : json.decode(string) : (object==null) ? Map() : object;
     return new PaymentDetail(
        AccountNumber             : map["AccountNumber"] as String,
        Amount                    : map["Amount"] as double,
        ChargeTypeID              : map["ChargeTypeID"] as int,
        CustomerNames             : map["CustomerNames"] as String
     );
  }

}

Below is it's implementation

 PaymentDetail payDetail =  new PaymentDetail().from(object: new Map());

 PaymentDetail otherPayDetail =  new PaymentDetail().from(object: {"AccountNumber": "1234", "Amount": 567.2980908});

Once again, this is simplistic and tedious to clone throughout the project but it works for simple cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!