Copy class instance

Well, ObjectUtil.copy is a good method for copying objects. But after I had a lot of problems copying it to other classes, I think this is not the solution I want.

How do you approach copying / cloning instances of the class you defined? Maybe define a function with a class to copy it?

It's great that most variables are passed by reference to flex, but sometimes it’s annoying without having control over it (sorry, I'm too used to simple C).

Thank!

UPDATE:

To be more precise, since I can't get ObjectUtil.copy () to work with a custom class ... is there a way to copy, using serialization, a custom class? Have you successfully used a ByteArray instance with a custom class?

Thanks for all the answers.

+3
source share
4 answers

If you have control over the entire class hierarchy, I recommend implementing an interface clone()in each class. This is tiring, but will pay off as complexity increases.

(Excuse me if the syntax is a bit off, it has been a while)

// define a "cloneable" interface
public interface ICloneable {
  function clone() : Object;
}

For each class, we implement the method ...

public class MyClass1 implements ICloneable {
  ...
  public function clone() : Object {
    var copy:MyClass1 = new MyClass1();

    // copy member variables... if it is a user-defined object,
    // make sure you call its clone() function as well.

    return copy;
  }
}

To create a copy of an object, just call the function clone().

var copy:MyClass1 = original.clone();

As a note, both Java and .NET seem to have adopted methods cloneon their base classes Object. I do not know a similar method for the ActionScript class Object.

+2
source

, clone , ByteArray, , , , . .

Senocular .

function clone(source:Object):* {
  var copier:ByteArray = new ByteArray();
  copier.writeObject(source);
  copier.position = 0;
  return(copier.readObject());
}

!

+3

ObjectUtil.copy ByteArray . , ByteArray , - . , registerClassAlias ​​.

:

//one time globally to the application.
registerClassAlias(getQualifiedClassName(CustomClass), CustomClass); 

//then
var c1:CustomClass = new CustomClass();
c1.name = "customClass";
var c2:CustomClass = ObjectUtil.copy(c1);

trace(ObjectUtil.toString(c1))
trace(ObjectUtil.toString(c2))
+3

:

  • a clone

Both of them allow you to determine what exactly the copy does — you may want some things to be copied shallow and others to be deep.

0
source

Source: https://habr.com/ru/post/1779009/


All Articles