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

How would I make 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)

+5
source share
3 answers

Dart Code:

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

More about this document: http://www.dartlang.org/articles/reflection-with-mirrors/

(From Gilad Brac)

+6
source

Using built_mirrors , you can do it like this:

 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}"); } 
0
source

This problem bothered me until I thought that I could implement a crude from method to handle the conversion of encoded Json or Dart Maps objects / strings to the desired class.

Below is a simple example that also processes null values ​​and accepts JSON (as a 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 the implementation

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

Once again, it is easy and tedious to clone an entire project, but it works for simple cases.

0
source

Source: https://habr.com/ru/post/1486943/


All Articles