Is there an analogue of memcpy in Java?

It is necessary to create a copy of the class instance:

 myClass a = new myClass(); /* * ... действия над a */ myClass b; b = a; // b ссылается на a //Нужно создать копию класса a 

    3 answers 3

     b = a.clone(); 
    • Note that this is not literally equivalent. Pure memcpy is not available for copying class instances. - cy6erGn0m
    • Familiarized with this method. I understood correctly, if memcpy copies the entire specified area of ​​memory, then .clone() copies only the class fields? If the class fields are other classes, should they also inherit from Clonable ? - Ildar
    • Not. Deep cloning is not performed by default. Just copy the links. - cy6erGn0m
    • And how do you clone all objects within a class, all sub-objects and sub-sub-sub-sub-under ..... objects? - Anton Mukhin
    • 2
      code.google.com/p/cloning <br/> Although there is a lot of talk on the topic. Search for "java deep clone" keywords - cy6erGn0m

    I add that in addition to variations with deep copy implementations, the following options are also possible:

    Using copyOf for primitive types (с версии 1.6) :

     byte[] src = {1, 2, 3, 4}; byte[] dst = Arrays.copyOf(src, src.length); 

    Serialization-deserialization of objects, optimized taking into account the fact that we only want to copy a fragment of memory:

    See here.

      To copy a class - there are different ways. The difficulty is that you can have a reference to the base class, while the actual instance is a child class.

      For example, there is a base class Animal and children: Cat (Animal) and Dog (Animal).

      Animal a1 = new Cat(); you need to do something like: Animal a2 = copy(a);

      This is where the fun begins. There are several options

      The dumbest option can be done like this:

       if(a1 insfanceof Cat){ a2 = new Cat(); a2.field = a1.field; } if(a1 insfanceof Dog){ a2 = new Dog(); a2.field = a1.field; } 

      But then the principle of SOLID is violated. You should not know about a specific implementation, but should work with abstraction.

      The second way is to make Clonable. It must be implemented in each subclass. It turns out that you also need to go down in each subclass and implement something there. It turns out quite long.

       public class Test { public static class Animal implements Cloneable{ public Animal clone() throws CloneNotSupportedException { return (Animal) super.clone(); } } public static class Cat extends Animal{ public Cat clone() throws CloneNotSupportedException { return (Cat) super.clone(); } } public static void main(String[] args) throws CloneNotSupportedException { Animal a1 = new Cat(); Animal a2 = a1.clone(); System.out.println(a1); System.out.println(a2); } } 

      The third option is through reflection. The fourth option is through serialization-deserialization. The fifth option is to take the source of openJDK and make your java with memcpy.