java - 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 方库开放
解决方案
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
推荐阅读
- php - 找不到 php-curl 包
- json - Swiftui:从 JSON 中获取动态颜色渐变?
- python - 为什么一个字符串会导致整个 pandas DataFrame 不是数字的?
- android - Amplify.observe 不根据对 DynamoDB 的更改进行更新
- java - 将字母从字符串转换为数字
- loops - 如何在 Tcl 的一个参数中使用带有多个变量的 puts?
- php - PHP连接被拒绝
- swift - 通过匹配对 Realm 中的过滤结果进行排序
- javascript - React JS-发送POST请求时CORS缺少允许标头
- python - ProjError:x、y、z 和时间必须相同大小