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)

有帮助吗?

解决方案

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)

其他提示

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

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.

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