Easy deep clone method for ActionScript 3.0

Posted by on Feb 10, 2009 in ActionScript, Flash, Flex6 comments

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;

Tags: , ,


» Comments RSS Feed
  1. Hey Dennis!
    Man… nice that you have blogged about it, but my blog is http://www.filipesilvestrim.com. That blog that you linked have just a copy of my post ;)

  2. Hey Filipe,
    Thanks for letting me know. I’ve changed the link!

  3. [...] a previous post I talked about an easy deep cloning method I found and which I tweaked a [...]

  4. 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.

  5. [...] were however a few solutions that were hacked together to provide the same functionality (here and here). These solutions have one big problem though, they don’t work with classes which have [...]

  6. 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 comment