Posts Tagged reflection
Dynamic Classes Gotcha!
Posted by admin in Uncategorized, actionscript, flex, flex builder on April 6th, 2010
We recently started using dynamic classes to assist with unknown data formats. It’s a pretty powerful feature of the language. It comes with a price in that you don’t get strong typing nor intellisense on the dynamic properties. But, there are cases where it can serve great purpose.
One of the things you have to keep in mind though is that since the class is dynamic, the compiler can’t provide the linkage for you to do something like:
var someValue:SomeClass = someObject as SomeDynamicClass;
The compiler won’t complain, but, you will as you scratch your head trying to understand why someValue == null all the time. The lack of information at compile time is the obvious culprit.
But, I have found a decent workaround. Provide a constructor for the dynamic class that takes and Object as an optional parameter. If you pass in a parameter, call the helper function to populate the object. Here I’m using a form of reflection to do this dynamically so I don’t have to hand write all the properties.
dynamic public class SomeDynamicClass
public function SomeDynamicClass(obj:Object=null)
{
if ( obj )
this.populateMe(obj);
}
private function populateMe(source:Object):void
{
var destinationList:XML = describeType(this);
for each ( var propName:XML in destinationList..variable )
{
if ( source.hasOwnProperty( propName.@name ) )
{
var cls:Class = getDefinitionByName(propName.@type) as Class;
this[propName.@name] = source[propName.@name] as cls;
}
}
}
Later on, when you get some generic Object, like from ArrayCollection.getItem, you don’t do the normal cast but instead create a new instance passing in the Object.
var someValue:SomeClass = new SomeDynamicClass(someObject);
Hope that helps.