10

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)

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Both 'first' and 'classes' properties are not on LibraryMirror any more (I'm using 30188). How would you do this with Dart v1?
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.