I've had issues with the builtin ObjectUtil.clone()
and ObjectUtil.copy()
methods. Thats why I created my own version that uses introspection instead using ByteArray.
One method copies all properties from one instance to another:
private static const rw:String = "readwrite";
public static function copyProperties(source:Object, target:Object):void {
if (!source || !target) return;
//copy properties declared in Class definition
var sourceInfo:XML = describeType(source);
var propertyLists:Array = [sourceInfo.variable, sourceInfo.accessor];
for each (var propertyList:XMLList in propertyLists) {
for each (var property:XML in propertyList) {
if (property.@access == undefined || property.@access == rw) {
var name:String = property.@name;
if (target.hasOwnProperty(name)) target[name] = source[name];
}
}
}
//copy dynamic properties
for (name in source)
if (target.hasOwnProperty(name))
target[name] = source[name];
}
The other creates a complete clone of an object by copying all its properties to a new instance:
public static function clone(source:Object):* {
var Clone:Class = getDefinitionByName(getQualifiedClassName(source)) as Class;
var clone:* = new Clone();
copyProperties(source, clone);
return clone;
}