Create an instance of an object from a String in Dart?

和自甴很熟 提交于 2019-11-27 07:04:35

问题


How would I do the Dart equivalent of this Java code?

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

(From Jeff Gardner)


回答1:


The Dart code:

ClassMirror c = reflectClass(MyClass);
InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);
var o = im.reflectee;

Learn more from this doc: http://www.dartlang.org/articles/reflection-with-mirrors/

(From Gilad Bracha)




回答2:


Using built_mirrors you can do it next way:

library my_lib;

import 'package:built_mirrors/built_mirrors.dart';

part 'my_lib.g.dart';

@reflectable
class MyClass {

  String myAttribute;

  MyClass(this.myAttribute);
}

main() {
  _initMirrors();

  ClassMirror cm = reflectType(MyClass);

  var o = cm.constructors[''](['MyAttributeValue']);

  print("o.myAttribute: ${o.myattribute}");
}



回答3:


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.



来源:https://stackoverflow.com/questions/17181108/create-an-instance-of-an-object-from-a-string-in-dart

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