Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 644
Seth Ladd Avatar asked Jun 19 '13 00:06

Seth Ladd


People also ask

How do you create an instance of a class in darts?

Syntax: var object_name = new class_name([ arguments ]); In the above syntax: new is the keyword use to declare the instance of the class.

How do you convert a string to a class name in Dart?

String type = MyClass(). runtimeType. toString();

Is string an object in Dart?

In Dart, we work with objects. Even numbers or string literals are objects.

What is an instance in Dart?

Instance Method in Dart:Unless the method is declared as static it is classified as an instance method in a class. They are allowed to access instance variables. To call the method of this class you have to first create an object.


1 Answers

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)

like image 54
Seth Ladd Avatar answered Sep 29 '22 05:09

Seth Ladd