AS3 invoking class from linkage by string

Today I was programming a game and I run over a problem, I had to invoke a Class by its string name.
It can easly be solved by using a switch like:

var className:String = "ClassNameOnTheLibrary1";
var gamePhase:MovieClip;
switch(className){

case "ClassNameOnTheLibrary1":
gamePhase = new Phase1();
break;

case "ClassNameOnTheLibrary2":
gamePhase  = new Phase2();
break;

}

Now what if you have to have thousands of cases. I had only 10 and found a pretty good solution.

Here it goes:
first import the class getDefinitionByName from flash utils.

import flash.utils.getDefinitionByName;

then you just cast your string as a Class and invoke its constructor:

var ClassDefinition:Class = Class( getDefinitionByName( "ClassNameOnTheLibrary1" ) );
var gamePhase:MovieClip = new ClassDefinition();

Thats it, hope I saved you some time.

2 Comments Add yours

  1. Tnelson says:

    Your blog is so informative … ..I just bookmarked you….keep up the good work!!!!

  2. Nick says:

    awesome – many thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s