Monday, February 9, 2009

How To Call Methods from a External SWF (Reflection in Flex )

While loading the swf from a external source , we are always wondering what all methods it may have , the developers have to seek help from the swf coders to get the methods and commnets for the methods which they have created, sometimes the developers provide the swf but fail to provide a meaningful API with which you can interact with the swf.

The Phenomenon of seeing the properties and methods of the class is know as 'reflection', to achieve this in flex we need to use the SWF loader to load the swf into the application as follows

var swfUrl : String = "";// path to your swf
var req: URLRequest = new URLRequest(swfUrl);
var loader : URLLoader = new URLLoader(req);

Now we will be using the class to get the remote objects .Once you have the class names it was a matter of the actual introspection to see the available methods. To do this you can use the getDefinition method of the ApplicationDomain class in Flex
var classUsed:Class = loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class;

Here we get a XMl with all the methods and variables ...
var remoteSWF:Object = loader.content as Object;

Just call the method you wish to call from the SWF
remoteSWF.methodToBeCalled(); // calling the desired method with its name


Varun Rathore

No comments:

About Me