diff --git a/hutool-core/src/main/java/cn/hutool/core/clone/DefaultClone.java b/hutool-core/src/main/java/cn/hutool/core/clone/DefaultClone.java new file mode 100644 index 000000000..acfb5f6c4 --- /dev/null +++ b/hutool-core/src/main/java/cn/hutool/core/clone/DefaultClone.java @@ -0,0 +1,29 @@ +package cn.hutool.core.clone; + + +import java.lang.reflect.Method; + +public interface DefaultClone extends java.lang.Cloneable { + + /** + * 浅拷贝 + * 功能与 {@link CloneSupport#clone()} 类似, 是一种接口版的实现 + * 一个类,一般只能继承一个类,但是可以实现多个接口,所以该接口会有一定程度的灵活性 + * + * @param T + * @return obj + */ + @SuppressWarnings({"unchecked"}) + default T clone0() { + try { + final Class objectClass = Object.class; + final Method clone = objectClass.getDeclaredMethod("clone"); + clone.setAccessible(true); + return (T) clone.invoke(this); + } catch (Exception e) { + throw new CloneRuntimeException(e); + } + } +} + + diff --git a/hutool-core/src/test/java/cn/hutool/core/clone/DefaultCloneTest.java b/hutool-core/src/test/java/cn/hutool/core/clone/DefaultCloneTest.java new file mode 100644 index 000000000..c2c45285a --- /dev/null +++ b/hutool-core/src/test/java/cn/hutool/core/clone/DefaultCloneTest.java @@ -0,0 +1,86 @@ +package cn.hutool.core.clone; + + +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class DefaultCloneTest { + + @Test + public void clone0() { + Car oldCar = new Car(); + oldCar.setId(1); + oldCar.setWheelList(Stream.of(new Wheel("h")).collect(Collectors.toList())); + + Car newCar = oldCar.clone0(); + Assert.assertEquals(oldCar.getId(),newCar.getId()); + Assert.assertEquals(oldCar.getWheelList(),newCar.getWheelList()); + + newCar.setId(2); + Assert.assertNotEquals(oldCar.getId(),newCar.getId()); + newCar.getWheelList().add(new Wheel("s")); + + Assert.assertNotSame(oldCar, newCar); + + } + +} + +class Car implements DefaultClone { + private Integer id; + private List wheelList; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public List getWheelList() { + return wheelList; + } + + public void setWheelList(List wheelList) { + this.wheelList = wheelList; + } + + @Override + public String toString() { + return "Car{" + + "id=" + id + + ", wheelList=" + wheelList + + '}'; + } +} + + +class Wheel { + private String direction; + + public Wheel(String direction) { + this.direction = direction; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + @Override + public String toString() { + return "Wheel{" + + "direction='" + direction + '\'' + + '}'; + } +} + +