Swf Class Explorer for AS3
Friday, July 18th, 2008The ApplicationDomain class in Actionscript 3 is a really handy class. It allows you to get any class from a loaded (or the current) swf and instantiate it.
ApplicationDomain currently has two public methods, hasDefinition(name:String):Boolean and getDefinition(name:String):Object. The simplicity of using these classes is a real treat, instantiating a class is as easy as
var myInstance:DisplayObject = new (ApplicationDomain.currentDomain. getDefinition("com.flassari.MyClass"));
The biggest pain about the ApplicationDomain class is however its lack of a function for displaying all of the classes in a particular ApplicationDomain.
ApplicationDomain.getAllDefinitions():Array would be great! But unfortunately we must find our own way of getting around this flaw… so here it is!
I give you, the SwfClassExplorer class. Its usage is simple, as it has only one static function, getClasses(bytes:ByteArray):Array. To use it you must provide it with the bytes of the swf clip you want to explore. Here is an example of basic usage:
public function init():void { // Load the swf var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoaderDataFormat.BINARY; urlLoader.addEventListener(Event.COMPLETE, onSwfLoaded); urlLoader.load(new URLRequest("pathToSwf")); } private function onSwfLoaded(e:Event):void { // Get the bytes from the swf var bytes:ByteArray = ByteArray(URLLoader(e.currentTarget).data); // And feed it to the SwfClassExplorer var traits:Array = SwfClassExplorer.getClasses(bytes); for each (var trait:Traits in traits) { trace(trait.toString()); // The full class name } }
I’ve prepared an example to demonstrate how it works.
First we have the Primitives.swf file. It will act as our “MovieClip library”. Its library consists of four movieclips, Box, Circle, Polystar and Triangle, each with its linkage class set to its library name:
Next we have the Example.swf file. It loads any swf file (Primitives.swf is in the path box by default) and lists all of the classes found in it. If the user clicks any of the classes, it will try to instantiate the class using no parameters (exceptions will be caught and displayed to the user) and if is or extends DisplayObject it will display it in the preview area.
You can get the example files and source code here or the compiled swc here.
*UPDATE!
The code is now on GitHub: https://github.com/Flassari/Swf-Class-Explorer
And apparently the swc file has gone MIA, I’ll upload it again if I have the time/can be bothered.