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!
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!