Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to instantiate a class from a dynamic var?

I have many objects of the same base type. I want to build a generic function to create them. Code sample :

class Grid extends Display { ....
class Start extends Display { ....

class MainClass {
  Grid grid;
  Start start;
  ....
}

in a MainClass method, instead of this :

start = new Start();
start.load(PATH);

grid = new Grid();
grid.load(PATH);

.... 

I would like to do something like this :

void _newDisplay(dynamicType, Display display) {
  display = new dynamicType();
  display.load(PATH);        
}

_newDisplay(Start, start);
_newDisplay(Grid, grid);

....

I read http://www.dartlang.org/articles/optional-types/ but did not find exactly what I wanted.

I also found Instantiate a class from a string but there is a comment saying : "Note: this might not work when compiled to JavaScript. The dart2js compiler doesn't yet fully support mirrors.". Is this "mirror" solution the only one available to make dynamic instantiation ?

like image 957
Eric Lavoie Avatar asked May 10 '13 16:05

Eric Lavoie


1 Answers

Dart doesn't support a direct way to do this. Usually we work around this by providing a closure that instantiates the type for us:

void _newDisplay(dynamicType, Display display) {
  display = dynamicType();
  display.load(PATH);        
}

_newDisplay(() => Start(), start);
_newDisplay(() => Grid(), grid);

Also see What are some good workarounds for dart's lack of static typing semantics?

like image 105
Florian Loitsch Avatar answered Oct 13 '22 23:10

Florian Loitsch