In ActionScript3, how do you get a reference to an object's class?
It's worth noting that the XML objects (XML, XMLList) are an exception to this (ie. (new XML() as Object).constructor as Class == null). I recommend falling back to getDefinitionByName(getQualifiedClassName) when constructor does not resolve:
function getClass(obj : Object) : Class
{
var cls : Class = (obj as Class) || (obj.constructor as Class);
if (cls == null)
{
cls = getDefinitionByName(getQualifiedClassName(obj));
}
return cls;
}
Note that getDefinitionByName will throw an error if the class is defined in a different (including a child) application domain from the calling code.
You can use the constructor
property if your object has been created from a class (from the docs: "If an object is an instance of a class, the constructor property holds a reference to the class object. If an object is created with a constructor function, the constructor property holds a reference to the constructor function."):
var classRef:Class = myObject.constructor as Class;
Or you can use flash.utils.getQualifiedClassName()
and flash.utils.getDefinitionByName()
(not a very nice way since this entails unnecessary string manipulation in the implementations of these library functions):
var classRef:Class = getDefinitionByName(getQualifiedClassName(myObject)) as Class;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With