AS3 Quick Tip: Get a Class reference from a String

When writing a game or another such type of program which requires parsing save data to workable data, you often have to write parsers. More often than not you have to write a switch statement to parse, say, a piece of xml representing that object. This process can be made easier if you can have a node in your xml that contains the name of the Class you want to instantiate. And heres how to do that :

var myClassString:String = "MyClass";
var classReference:Class = getDefinitionByName(myClassString) as MyClass;

var myNewInstance:MyClass = new classReference();

I’m using this method in a game engine i’m writing. I use it as part of my level parser as i have a large amount of library graphics in CS5 which all sub-class my LevelObject Class. This provides me an easy way to iterate through a list of objects in XML and instantiate them without having to write a ridiculous switch.

Peace

Bill

Tags: , , , , , , , , , , ,

  • http://topsy.com/www.wuup.co.uk/as3-quick-tip-get-a-class-reference-from-a-string?utm_source=pingback&utm_campaign=L2 Tweets that mention AS3 Quick Tip: Get a Class reference from a String | Wuup — Topsy.com

    [...] This post was mentioned on Twitter by Alan Hamlyn, Bill Nunney. Bill Nunney said: Wuup » Actionscript 3.0 AS3 Quick Tip: Get a Class reference from a String http://is.gd/dCzbO [...]