`

How to clone (duplicate) an object in ActionScript 3

    博客分类:
  • Flex
 
阅读更多
For a project I needed to clone an object of unknown type. And by clone I mean to create a new instance of that same type and then fill out all its properties (including getters and setters) to mirror the original object.

Thanks to a friend, I discovered the describeType function in AS3. But this alone will only take care of the copying part. To create an object of the same type as another one we use getDefinitionByName.

Although Flash reflection is pretty basic, with a little work it will do the trick.

Get the application files.

Here's the code:
< ?xml version="1.0" encoding="utf-8"?>
<mx :Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="init()">
</mx><mx :Script>
 < ![CDATA[
 
     import mx.controls.Alert;
 
     private var source:DataObject = new DataObject();
     private var cloneObject:DataObject;
 
 
     private function init():void {
 
         source.name = 'John Doe';
         source.howMany = 4.5;
         source.when = new Date(0);
         source.complexProp = new DataObject();
         source.complexProp.name = 'Name in sub-object';
 
         cloneObject = UtilFunctions.clone(source) as DataObject;
 
         Alert.show("Clone:\nname = " + cloneObject.name + "\nhowMany = " + cloneObject.howMany + "\nwhen = " + cloneObject.when + "\ncomplexProp.name = " + cloneObject.complexProp.name);
     }
 
     /**
 
      * describeType will produce this (for a DataObject instance):
      *
      * <type name="DataObject" base="Object" isDynamic="false" isFinal="false" isStatic="false">
 
           <extendsclass type="Object"/>
           <accessor name="isHandicap" access="writeonly" type="Boolean" declaredBy="DataObject"/>
 
           <variable name="howMany" type="Number"/>
           <accessor name="complexProp" access="readwrite" type="DataObject" declaredBy="DataObject"/>
 
           <variable name="name" type="String"/>
           <variable name="when" type="Date"/>
 
 
      *
      * */
 
 ]]>
 
</mx>


And the UtilFunctions.as file:

package
{
 import flash.utils.describeType;
 import flash.utils.getDefinitionByName;
 import flash.utils.getQualifiedClassName;
 
 public class UtilFunctions
 {
 
 
     public static function newSibling(sourceObj:Object):* {
         if(sourceObj) {
 
             var objSibling:*;
             try {
                 var classOfSourceObj:Class = getDefinitionByName(getQualifiedClassName(sourceObj)) as Class;
                 objSibling = new classOfSourceObj();
             }
 
             catch(e:Object) {}
 
             return objSibling;
         }
         return null;
     }
 
     public static function clone(source:Object):Object {
 
         var clone:Object;
         if(source) {
             clone = newSibling(source);
 
             if(clone) {
                 copyData(source, clone);
             }
         }
 
         return clone;
     }
 
     public static function copyData(source:Object, destination:Object):void {
 
         //copies data from commonly named properties and getter/setter pairs
         if((source) && (destination)) {
 
             try {
                 var sourceInfo:XML = describeType(source);
                 var prop:XML;
 
                 for each(prop in sourceInfo.variable) {
 
                     if(destination.hasOwnProperty(prop.@name)) {
                         destination[prop.@name] = source[prop.@name];
                     }
 
                 }
 
                 for each(prop in sourceInfo.accessor) {
                     if(prop.@access == "readwrite") {
                         if(destination.hasOwnProperty(prop.@name)) {
                             destination[prop.@name] = source[prop.@name];
                         }
 
                     }
                 }
             }
             catch (err:Object) {
                 ;
             }
         }
     }
 }
}


文章摘自:
http://blog.another-d-mention.ro/programming/how-to-clone-duplicate-an-object-in-actionscript-3/
分享到:
评论

相关推荐

    提示Trying to clone an uncloneable object of class Imagic的解决

    使用网上流传的一个程序实现pdf截图为png,需要使用Imagic扩展,安装后出现Trying to clone an uncloneable object of class Imagic提示,下面是具体的解决方法分享。

    Trying to clone an uncloneable object of class Imagic的解决方法

    在windows下安装完后提示:Fatal error: Trying to clone an uncloneable object of class Imagick in C:\www\hx\pdf_to_png.php on line 17 使用IIS和Apache均会有这个提示。经多次测试后,发现两种解决方法: 1....

    深入理解JavaScript中的对象复制(Object Clone)

    在深入探讨JavaScript中的对象复制(Object Clone)时,首先需要明确JavaScript中的对象复制分为浅复制(Shallow Copy)和深复制(Deep Copy)。浅复制指的是创建一个新对象,这个对象有着原始对象属性值的一份精确...

    Getting Started with OpenCart Module Development

    Getting Started with OpenCart Module Development gives you step-by-step explanations and illustrations on how to clone, customize, and develop modules and pages with OpenCart. This book shows you how...

    How To Run Rapid Clone (adcfgclone.pl) Non-Interactively (Doc ID

    How To Run Rapid Clone (adcfgclone.pl) Non-Interactively (Doc ID 375650.1)

    Clone Detection in Secure Messaging- Improving Post-Compromise

    Clone Detection in Secure Messaging- Improving Post-Compromise Security in Practice

    Object-Oriented Analysis and Design 第六章

    - Decorator pattern adds behavior or responsibilities to an object dynamically without affecting the behavior of other objects in the same class. - Facade pattern provides a simplified interface to a ...

    Object-C-MixinObject-C-MixinObject-C-Mixin

    It's a good start to understand how to write mixin in Object-C. ### Import ObjCMixin ```objc #import ``` ### Define and implement a module Declare a module. ```objc @module(MyModule) @property...

    Content authoring.zip

    Copy or duplicate an item Lock and unlock an item Edit a field in the Experience Editor Edit the website content Manage associated content Delete an item Edit the layout of an item Reset the ...

    Sortable前端框架

    scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) { data...

    flash ActionScript.3小技巧

    ### Flash ActionScript 3 小技巧详解 #### 1. 更改帧速率 在 Flash 开发过程中,有时我们需要更改动画的帧速率以适应不同的场景需求。ActionScript 3 提供了一个简单的方法来实现这一功能: ```actionscript // ...

    java Clone

    `clone`方法存在于Java的`java.lang.Object`基类中,所有Java类都默认继承自`Object`类,因此所有类都具备`clone`能力。 首先,要使用`clone`方法,我们需要确保类实现了`Cloneable`接口。`Cloneable`接口并没有...

    Geometry-Wars-Clone-Flash:用 actionscript 3 air (starling + AGAL) 编写的几何战争克隆

    《几何战争克隆》是一款基于ActionScript 3的空中(AIR)平台开发的游戏,它使用了Starling框架和AGAL着色器技术。这个项目是一个对经典街机游戏《几何战争》的致敬与复刻,旨在展示如何在Flash平台上实现高性能的2D...

    clone()示例源码

    通常,为了能够正确地克隆一个对象,你需要确保类的每个属性都是可克隆的,并且覆盖`Object`类中的`clone()`方法,声明为`protected`或`public`,因为默认它是`protected`的。 ```java public class MyClass ...

    java_clone用法

    public Object clone() throws CloneNotSupportedException { return super.clone(); } } // 示例代码 User user = new User(); user.name = "user"; user.age = 20; Account account = new Account(); ...

    How_to_Make_ASLR_Win_the_Clone_Wars__Runtime_Re-Randomization.pdf

    发表在NDSS‘16上的论How to Make ASLR Win the Clone Wars: Runtime Re-Randomization。这篇文章提出了一个RuntimeASLR的机制,让fork()出来的子进程内存空间地址重新随机化。 Background 在Apache,Nignx和OpenSSH...

    MapReduce-based Assembly Clone Search for Reverse Engineering.pdf

    It is also a common practice to discover exploits and vulnerabilities in existing software. However, it is a manually intensive and time-consuming process even for experienced reverse engineers. An ...

    Jlink-clone解决办法,替换文件.rar

    3. **识别设备**:在设备管理器中找到Jlink-clone设备,确认其当前的驱动状态和版本。这有助于了解是否已安装了非官方驱动。 4. **安装新驱动**:如果压缩包内包含驱动文件,可以通过双击运行安装程序,按照提示...

Global site tag (gtag.js) - Google Analytics