PDA

View Full Version : Dynamic Class Instantiation



McGuffin
May 9th, 2007, 06:33 PM
Alright, I solved this problem for AS2 and AS3, but it's not as elegant as I'd like.



import flash.utils.getDefinitionByName;
var className:String = "com.cfms.Navigation";
var classReference:Class = getDefinitionByName(className) as Class;
var classInstance:Object = new classReference();


This all works well and gravy if I've already defined the Navigation class once before, as such:



import com.cfms.Navigation;
var nav = new Navigation();
nav = null;


But I was wondering if there was any way possible to skip that last step, instead of having to add in all the manual instances? I understand this is so that Flash will compile the classes into the SWF document, but is there a more elegant way to do this?

senocular
May 9th, 2007, 06:39 PM
You dont even have to go so far as to instantiate it; you can just have the class reference in code

Navigation;
But you will at least need to do that or associate it with a movie clip symbol and check export in first frame. There really isn't any other way.

McGuffin
May 9th, 2007, 06:47 PM
Thanks for the quick reply Sen :)

McGuffin
May 9th, 2007, 07:32 PM
Sen, a quick followup:



var classInstance = new ClassReference();
// vs
var classInstance:Object = new ClassReference();


Using the Object datatype declaration leads to issues when I attempt to use:



addChild(classInstance);
/*
Error:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.display:DisplayObject.
*/


Are there any dangers in leaving the declaration out? I understand that in normal cases, not passing a datatype along would hurt performance. Would it in this case?

TheCanadian
May 9th, 2007, 07:53 PM
Use the as (http://livedocs.adobe.com/flex/2/langref/operators.html#as) operator to convert the type:

this.addChild(classInstance as DisplayObject);
Or type cast it:

this.addChild(DisplayObject(classInstance));

McGuffin
May 9th, 2007, 08:02 PM
Thanks, from one canadian to another ;)

TheCanadian
May 9th, 2007, 08:07 PM
Go team :hoser: