PDA

View Full Version : Reflection in Flex & AS 3


Stealth86
08-07-2008, 05:36 PM
I have a factory function that returns a number of different objects. When I get the object back, what's the best way to discover it's type and cast it to such?

Here's the function:

private function createCMMObject(classname:String):CMMObject
{
switch (classname)
{
case "CMMRectangle":
return new CMMRectangle();
break;
case "CMMText":
return new CMMText();
break;
case "CMMCircle":
return new CMMCircle();
break;
case "CMMEllipse":
return new CMMEllipse();
break;
case "CMMPolygon":
return new CMMPolygon();
break;
case "CMMObject":
return new CMMObject();
break;
}

return null;
}

Each object returned is derived from CMMObject. What I would like to do in the function that calls this is discover the actual type of the CMMObject returned, and cast it to this type. Of course I won't know until runtime what it is that I've received.

It seems like there should be a way to query the object for what it is, and then store this into a Class variable that I could use for casting and object creation.

For example, I'd like to be able to write something like this ...

function psuedocode(classname:String):void
{
var obj:Object = createCMMObject(classname);
var type:Class = typeof(obj);

// ...

(obj as type).someMethodCall();

// ...
}

Does this look feasible? If so, can someone point me in the right direction?

Thanks all!

Stealth86
08-07-2008, 08:16 PM
I figured out a solution that seems to work well enough.

var c:Class = Class(getDefinitionByName(getQualifiedClassName(ob j)));

It's a bit round about, so if anyone has a better suggestion I'd be interested in hearing it.

hangalot
08-13-2008, 11:57 AM
well the reason you would use the abstract factory pattern and generate the class in a factory method is in order to derive your methods from a common interface. now you are going to cast it to a non common interface, thus going and coding against implementation rather than interface. you are on the right road here but the result is not ideal if you have to ask a class what type it is and then make a decision based on that.

swivelmaster
08-26-2008, 08:08 PM
Why not just case them as an interface that includes some kind of "type" parameter, which would be a string that references a constant? Then when the object comes in, do this:

function foo(object:ICMMObject):void{
switch (object.type){
case CMMObject.POLYGON:
doStuff();
break;
case CMMObject.RECTANGLE:
doOtherStuff();
break;
// etc. etc.
}
}