View Full Version : declare variable with type depending on string

09-06-2006, 02:42 PM
Hi folks,

i am trying to generate ui objects dynamically depending on a string.

so let's say, depending on the value of a string i want to create either
a "Panel" or a "Canvas". It works with a switch clause like this:

var wantedtype:String = "Panel";

// some code

switch (wantedtype) {
case "Panel":
var obj:Panel = new Panel();
case "Canvas":
var obj:Canvas = new Canvas();

is there an easier way to handle this or do i have to put all the types into cases?

Thank you in advance,

09-06-2006, 03:27 PM
declare it as type :*

09-06-2006, 03:41 PM

i already tried this, but i still have to specify the
object type somewhere, otherwise i get an TypeError 1010
when trying to define properties like this:

var obj:*;

obj.alpha = 1; <<< TypeError 1010

09-07-2006, 09:28 AM
You should declare it with a type which is a superclass of all the possible objects that you will assign to the variable. In case of Panel and Canvas, the highest class which is still a superclass of both is mx.core.Container. Now, later on, when you access a certain property of the variable, if the property is defined in the superclass (Container in the example), it will work. If, however, you are trying to assign a property that only belongs to Panel but not to Canvas, you will have to cast your obj to Panel ["Panel(obj)" or "obj as Panel"] before you can access the property. Makes sense?

09-07-2006, 09:37 AM
Check out also the ApplicationDomain class. Using it you can do instantiate classes from a classname passed as a string, doing something like this

function createContainer(className:String):Container {
var myClass:Class = ApplicationDomain.currentDomain.getDefinition(clas sName) as Class;
var obj:Container = (new myClass()) as Container;
return obj;

var p:Container = createContainer("mx.containers.Panel");
var c:Canvas = createContainer("mx.containers.Canvas");

Note that if you call that function with a className which is not a subclass of Container, the function will return null. This is because the "as" operator will return null when the casting fails. If you want it to fail with an exception, use "Container(new myClass())" casting instead.

09-07-2006, 09:44 AM
ya don't need Apllication.currentDomain for this, u can just use

import flash.utils.getDefinitionByName;

function createContainer(className:String):Container {
var myClass:Class = getDefinitionByName(className) as Class;
var obj:Container = (new myClass()) as Container;
return obj;
var p:Panel = createContainer("mx.containers.Panel");
var c:Canvas = createContainer("mx.containers.Canvas");Problem is here is that the compiler will not include classes unless it seems them being used. Using this method, it does not see that they are being used so you must define an instance of the classes somewhere for it to work.