Implement the clone method in Record which is the 2nd preview in Java 15 so that you can make a deep copy.
I don't think there is a particular scene to use this, but I may use it someday, so I'll use it as a memorandum.
The point is to make a clone in the constructor without using super.clone ()
.
Java 15(Oracle Open JDK) IntelliJ IDEA Community Edition Windows
ExampleRecord.java
public record ExampleRecord(String name, int age, ExampleDto dto) {
}
ExampleDto.java
public class ExampleDto {
private String name;
private int age;
private NodeDto node;
// setter, getter,toString omitted
}
NodeDto.java
public class NodeDto {
private String name;
// setter, getter,toString omitted
}
ExampleRecord.java
public record ExampleRecord(String name, int age, ExampleDto dto) {
@Override
public ExampleRecord clone() {
try {
return new ExampleRecord(this.name, this.age, this.dto.clone());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
ExampleDto.java
public class ExampleDto implements Cloneable {
private String name;
private int age;
private NodeDto node;
// setter, getter,toString omitted
@Override
public ExampleDto clone() throws CloneNotSupportedException {
ExampleDto copy = (ExampleDto) super.clone();
copy.node = this.node.clone();
return copy;
}
}
NodeDto.java
public class NodeDto implements Cloneable {
private String name;
// setter, getter,toString omitted
@Override
public NodeDto clone() throws CloneNotSupportedException {
return (NodeDto) super.clone();
}
}
Main.java
public class Main {
public static void main(String[] args) {
ExampleDto dto = new ExampleDto();
NodeDto nodeDto = new NodeDto();
nodeDto.setName("node1");
dto.setNode(nodeDto);
dto.setName("dto1");
dto.setAge(1);
ExampleRecord exampleRecord = new ExampleRecord("record1", 2, dto);
System.out.println("exampleRecord:"+exampleRecord);// 1
dto.setName("dto2");
nodeDto.setName("node2");
System.out.println("exampleRecord:"+exampleRecord);// 2
ExampleRecord clone = exampleRecord.clone();
System.out.println("clone:"+clone);// 3
dto.setName("dto3");
nodeDto.setName("node3");
System.out.println("clone:"+clone);// 4
}
}
1.
exampleRecord:ExampleRecord[name=record1, age=2, dto=ExampleDto{name='dto1', age=1, node=NodeDto{name='node1'}}]
2.
exampleRecord:ExampleRecord[name=record1, age=2, dto=ExampleDto{name='dto2', age=1, node=NodeDto{name='node2'}}]
3.
clone:ExampleRecord[name=record1, age=2, dto=ExampleDto{name='dto2', age=1, node=NodeDto{name='node2'}}]
4.
clone:ExampleRecord[name=record1, age=2, dto=ExampleDto{name='dto2', age=1, node=NodeDto{name='node2'}}]
In 1-> 2, the contents of Dto have changed, but in 3-> 4, it is a different instance, so dto.setName ("dto3");
andnodeDto.setName ("node3");
You can see that it is unaffected and cloned without any problems.
Recommended Posts