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
2010-07-06 14:55:21
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
2010-07-06 15:03:46
+1 depending on the situation, this could be an acceptable solution.
Matthew J Morrison
2010-07-08 02:13:49
+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
2010-07-06 14:59:36
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
2010-07-06 15:04:02
@Ponty - yes, it should work with any class - as @Ender noted, it must be fully qualified with appropriate package(s).
Matthew J Morrison
2010-07-06 15:09:19
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
2010-07-06 15:24:56
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
2010-07-06 15:01:27
+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
2010-07-06 15:06:45