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 ?

有帮助吗?

解决方案

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?

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