Creating an instance of a class that implements an interface based on the class name?
Is there a way to generate an instance of a class 开发者_如何学Cthat implements an interface based on the name of the class?
I am trying:
var ClassReference:Object = getDefinitionByName("movement.OuterSpaceMovement") as IMovement;
var m:IMovement = new ClassReference as IMovement;
trace("startup..." + m);
-But I am getting an error message ReferenceError: Error #1065 (OuterSpaceMovement) not defined.
I have several classes that implement the same interface (IMovement) but I need to be able to generate new instances of these classes and then pass these instances as a datatype (IMovement datatype) to other classes...
So then I tried:
var ClassReference:Class = getDefinitionByName("OuterSpaceMovement") as Class;
var m:IMovement = new ClassReference() as IMovement;
and this doesn't seem to work...but the following
var m:IMovement = new OuterSpaceMovement();
does??
Your ClassReference should be of type Class, so:
var ClassReference:Class = getDefinitionByName("movement.OuterSpaceMovement") as Class;
var m:IMovement = new ClassReference() as IMovement;
This should work, unless there is a problem with the class definition (it must be included in the build, so you have to import OuterSpaceMovement at least once somewhere in your program, or include it explicitly in your build settings or compiler options).
And, of course, OuterSpaceMovement must implement IMovement. ;)
精彩评论