PDA

View Full Version : Objects on the fly



worthington747
February 12th, 2008, 10:59 PM
For the sake of writing less code, I looking for a solution for creating objects with a class declaration stored in a String.

How would the following object instantiation be writen to dynamically call the creation of objects using the following method?




var dynaBall:String="RedBall"
var myBall=new dynaBall()
//where RedBall exists as a library class


Any help would be greatly appreciated

Sirisian
February 12th, 2008, 11:05 PM
http://en.wikipedia.org/wiki/Factory_object

use enumerations.

TheCanadian
February 12th, 2008, 11:12 PM
Look into flash.utils.getDefinitionByName

McGuffin
February 12th, 2008, 11:36 PM
import flash.utils.getDefinitionByName;

var classStr:String = "custom.package.MyClass";
var classCls:Class = getDefinitionByName(classStr) as Class;
var instance:Object = new classCls("parameters", "too");


At some point, you need to add a reference to the class so that the code is compiled at compile-time, as getDefinitionByName will not load the class in dynamically. So you need to reference it somewhere like so:



import custom.package.MyClass;
MyClass;


This is sufficient to make sure you have access to it through getDefinitionByName.

worthington747
February 13th, 2008, 10:12 AM
Phenomenal work guys.
AS3 is really pulling its weight.

McGuffin
February 13th, 2008, 05:55 PM
No problems mate. You could do this in AS2 as well, with an undocumented class. Adobe likes to tuck away the fun stuff ;)

jbuda
February 20th, 2008, 05:58 AM
how can this be done with as2?

McGuffin
February 20th, 2008, 02:01 PM
// AS2
import mx.utils.ClassFinder;
import com.custom.CustomClass;
CustomClass;

// elsewhere in the movie
var className:String = "com.custom.CustomClass";
var classInstance = new ClassFinder.findClass(className) ("parameters", "here");