views:

42

answers:

4

Is it possible to have a string "ClassA" and use it in order to instantiate a real ClassA in my application?

A: 

Would it be impossible to use a conditional statement?

if (mystring == "ClassA")
{
   new ClassA()
}
Peter
Not the best way to handle this, Peter. It might work if you had like two different classes and needed a quick way to toggle between them - though even then there are better ways.The problem is that 1) there's a chance that myString != any of your predefined classes, 2) you'd have to manually add every possible contingency to your list of conditions, 3) maintaining this and troubleshooting would be next to impossible on a larger project. Much better to use getDefintionByName, as Matthew suggests above.
Myk
+1 depending on the situation, this could be an acceptable solution.
Matthew J Morrison
+4  A: 

Take a look at flash.utils.getDefinitionByName. You should be able to use that to get a class object from a string of the class name.

Matthew J Morrison
note that this has to be a fully qualified name, so if your class is defined in `com.namespace.subspace.MyClass`, you should have `var MyClass:Class = getDefinitionByName("com.namespace.subspace::MyClass") as Class; var myObj = new MyClass();`
Ender
@Ponty - yes, it should work with any class - as @Ender noted, it must be fully qualified with appropriate package(s).
Matthew J Morrison
I have a png image on Library that i have declared it via Properties as Background class which extends BitmapData. When i type: var BMDClass:Class = getDefinitionByName( "Background" ) as Class; i get: variable Background is not defined!!
Ponty
A: 

You can use

Eval("new "+myString+"()");

or possibly even

new Eval(myString)();

but I'm not sure Actionscript will support the second one.

Kendrick
I should note that my knowledge only extends to actionscript 2...
Kendrick
Yeah, eval was removed in AS3
Ender
+1  A: 

You can use the getDefinitionByName in the flash.utils package

var ClassReference:Class = getDefinitionByName("ClassA") as Class;

You will need the full path to the name so for example say mypackage.stuff.ClassA the call would like

var ClassReference:Class = getDefinitionByName("mypackage.stuff.ClassA") as Class;
var instance:Object = new ClassReference();

Then use can use instance to do your methods

instance.methodname();

Remember if you want to add it to the Display List you will have to cast it as a DisplayObject

addChild(DisplayObject(instance));
phwd
grr I type slow :(
phwd