首页 > 解决方案 > Java中浅拷贝检查的通用实用程序

问题描述

Java中是否有通用实用程序来检查浅拷贝的相等性?在给定的示例中,如何在不推出我自己的 equals() 实现的情况下验证浅拷贝

public class ClonableExample {
    public static class ClonableObject implements Cloneable, Serializable {
        @Override public ClonableObject clone() throws CloneNotSupportedException {return (ClonableObject) super.clone();}
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        ClonableObject b = new ClonableObject();

        System.out.println(b != b.clone());
        System.out.println(b.equals(b.clone())); // Reference check fails
        System.out.println(Objects.equals(b, b.clone())); // Nothing fancy but still a reference check that fails
        System.out.println(Objects.deepEquals(b, b.clone())); // Reference check + Arrays.equals checks both of which fail
    }
}

如果在核心 java 中不可用,则向 3rd 方库开放

标签: java

解决方案


EqualsBuilder (Apache Commons Lang API)->摇篮group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'

public static class CloneableObject implements Cloneable, Serializable {
    @Override 
    public CloneableObject clone() throws CloneNotSupportedException {
        return (CloneableObject) super.clone();
    }
}

System.out.println(EqualsBuilder.reflectionEquals(b, b.clone(), true)); // true

推荐阅读