Search code examples
actionscript-3apache-flexactionscript

copy method of util class is not working


I am having a class Employee as:

public class Employee
{
    public var name:String;
    public function Employee(name:String)
    {
        this.name = name;
    }
}

Now I am trying to create copy of an ArrayCollection of employees using ObjectUtil as:

protected function button1_clickHandler(event:MouseEvent):void
{
    var newEmployees = ObjectUtil.copy(employees);
    for each(var emp:Employee in newEmployees) {
        Alert.show(emp.name);
    }

}

But it is throwing exception:

Main Thread (Suspended: TypeError: Error #1034: Type Coercion failed: cannot convert Object@ef41a19 to objectutil.Employee.)
objectutil::ObjectUtilCopyCheck/button1_clickHandler
objectutil::ObjectUtilCopyCheck/___ObjectUtilCopyCheck_Button1_click

Can anyone identify what is wrong here? TIA.


Solution

  • The method copy internally makes copy using native serialization technique:

    public static function copy(value:Object):Object
    {
        var buffer:ByteArray = new ByteArray();
        buffer.writeObject(value);
        buffer.position = 0;
        var result:Object = buffer.readObject();
        return result;
    }
    

    If we use remoting tag then it is easy. For example:

    //assume employee has [RemoteClass] metadata. 
    var newEmployees = Employee (ObjectUtil.copy(emp));
    

    Else you need to register this class as (assuming that com.app.vo.Employee is the package of class Employee ):

    registerClassAlias("com.app.vo.Employee",Employee);
    //Now we can copy and caste
    var newEmployees = Employee (ObjectUtil.copy(emp));
    

    Hope this will help you.