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

前端 未结 3 1462
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 05:12

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

Class c = Class.forName(\"mypackage.MyClass\");
Const         


        
相关标签:
3条回答
  • 2020-12-11 05:19

    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}");
    }
    
    0 讨论(0)
  • 2020-12-11 05:36

    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)

    0 讨论(0)
  • 2020-12-11 05:41

    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.

    0 讨论(0)
提交回复
热议问题