Posted by Doug Hays on the 25th of September, 2008 at 12:51 pm under Flex.    This post has no comments.

I just ran into an interesting issue with ObjectUtil and its handy Copy function.  After performing a copy, I was attempting to cast the resulting object and the overall result was null:

oldField = new Field();
newField = ObjectUtil.copy(oldField) as Field;
//newField is null 

Thankfully, a quick trip to Google helped me find the solution 

I added this to my Field class:

[RemoteClass(alias="com.eastfacesoftware.Field")]
public class Field {...}

and I was a step further.  My last hurdle was using the Copy function on subclasses of Field.  As you might guess, you need to define the RemoteClass metadata on every class that you intend to copy. After I did this, ObjectUtil was again on my list of favorite ActionScript classes.

The reason?  ObjectUtil.Copy() uses AMF to serialize and de-serialize the original object to create the copy.  If AMF doesn’t have specific knowledge of your class, it will not return an object that will cast properly.

Thanks to Darron Schall for this helpful tip.