Can you make an object copy in Java?
MinhaClasse mc = new MinhaClasse();
MinhaClasse mc2 = mc;
But I wanted to make changes to mc2
without affecting mc
.
Can you make an object copy in Java?
MinhaClasse mc = new MinhaClasse();
MinhaClasse mc2 = mc;
But I wanted to make changes to mc2
without affecting mc
.
Just override the method Object#clone
, but your class needs to implement the Cloneable
interface. :
By convention, classes implementing this interface should replace
Object.clone
(which is protected) by a public method.
Using the example of MinhaClasse
used in the question, this would look like this:
public class MinhaClasse implements Cloneable {
// Atributos e métodos
@Override
public MinhaClasse clone() throws CloneNotSupportedException {
return (MinhaClasse) super.clone();
}
}
This would suffice to call the clone
method this way:
MinhaClasse meuObjeto = new MinhaClasse();
MinhaClasse meuOutroObjeto = meuObjeto.clone();
The correct method to create copies, duplicate, or clone objects is implementing the clone()
and the interface Clonable . This allows you to define exactly the values that will be copied and even clone object contained in the main object, if any.
However, depending on the context, there are other alternatives that may be feasible. For example, if the idea is to just copy a Java Bean with simple attributes, getters and setters , then the # / strong>. There is also the cloneBean()
that copies attributes from one object to another.
Another option, if the class is serializable, is to perform the serialization of the class followed by deserialization. Okay, you have an exact copy.
Of course it is not recommended to use the two methods mentioned above for such a simple case, but they can be useful for developing frameworks or very specific functionalities.
One of the scenarios where I used this was in a system that literally had hundreds of ever-changing Java Beans. It was not feasible to create and maintain the copyProperties()
method in all classes.
Yes, just set the Constructor method
class MinhaClasse {
private String str;
public MinhaClasse (MinhaClasse outro) {
this.str= outro.str; // tens acesso directo
}
}
All objects have a clone method that by default allows objects to be copied. Good practices dictate that you should define your copying method.
After defining this method, it is simple to copy the objects. You can simply do the following:
MinhaClasse mC = new MinhaClasse();
....(fazer algo com o objecto)
mc.Update();
MinhaClasse mC2(mc);
....(fazer algo com o objecto)
mC2.Update() <- esta alteração apenas irá afectar mC2!
In response to your comment. If your class MyClass has as members other classes than primitive type (int, string, ...) then those classes must also have defined copy constructors. For example.
class ClasseA {
private ClasseB b;
private String str;
ClasseA (ClasseA outro) {
this.b(outro.b) (aqui tens que garantir que a ClasseB possui um constructor de copia ou método =)
this.str= outro.str; // tens acesso directo
}
}
EDIT:
To all those who are suggesting implementing the Cloneable interface and setting the clone () method I suggest reading the following articles. Mainly reading the Effective Java:
I leave here just one more quote from Josh Bloch
"The Cloneable interface was intended as a mixin interface for objects to advertise that they allow cloning. Unfortunately it fails to serve. this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order to implement the interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable and largely undocumented protocol "