Easy deep clone method for ActionScript 3.0

UPDATE: I’ve made this made more flexible. Read this.

I stumbled upon this method via the ActionScript 3 Design patterns blog. This method is commonly used in Java to make a deep copy of an object. I tried the example but couldn’t get it to work. When I casted bytes.readObject() it always returned null. I found a solution for that on this blog. I put it all together in one method:

package com.rozengain.cloning
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;

	public class MyClass
		public var property1		: String;
		public var property2 		: Array;

		public function clone() : MyClass
			registerClassAlias( "com.rozengain.cloning.MyClass", MyClass );
			var bytes : ByteArray = new ByteArray();
			bytes.writeObject( this );
			bytes.position = 0;
			return bytes.readObject() as MyClass;
  • Delicious
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • Twitter

6 thoughts on “Easy deep clone method for ActionScript 3.0

  1. Hey, this is great. I’m wondering if this would help with the issue of communicating between closed ApplicationDomains, where you can’t cast Class from one AppDomain to another. Will chat to you about this.

  2. lifechamp says:

    Any way to make it generic and work on any object with just 1 copy of this nice little code in one’s sources, or, seeing as as3 has no user-defined generics, is that just not possible?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>